#ifndef __SW_H__
#define __SW_H__


#define SW_VERSION               "1.0.0 WIP"
#define SW_HAS_VIEWPORT          // Viewport WIP branch
#define SW_HAS_DOCK              // Docking WIP branch

//-----------------------------------------------------------------------------
// [SECTION] Header mess
//-----------------------------------------------------------------------------

// Includes
#include <stdio.h>
#include <float.h>                  // FLT_MIN, FLT_MAX
#include <stdarg.h>                 // va_list, va_start, va_end
#include <stddef.h>                 // ptrdiff_t, NULL
#include <string.h>                 // memset, memmove, memcpy, strlen, strchr, strcpy, strcmp

// Define attributes of all API symbols declarations (e.g. for DLL under Windows)
// SW_API is used for core imgui functions, SW_IMPL_API is used for the default backends files (mgui_impl_xxx.h)
// Using  imgui via a shared library is not recommended, because we don't guarantee backward nor forward ABI compatibility (also function call overhead, as  imgui is a call-heavy API)
#ifdef _WIN32
#ifdef _SW_EXPORT_
#define SW_API __declspec(dllexport)
#else
#define SW_API __declspec(dllimport)
#endif
#else
#define SW_API
#endif

//#ifndef SW_API
//#define SW_API
//#endif

#ifndef SW_IMPL_API
#define SW_IMPL_API              SW_API
#endif

// Helper Macros
#ifndef SW_ASSERT
#include <assert.h>
#define SW_ASSERT(_EXPR)            assert(_EXPR)                               // You can override the default assert handler by editing imconfig.h
#endif
#define SW_ARRAYSIZE(_ARR)          ((int)(sizeof(_ARR) / sizeof(*(_ARR))))     // Size of a static C-style array. Don't use on pointers!
#define SW_UNUSED(_VAR)             ((void)(_VAR))                              // Used to silence "unused variable warnings". Often useful as asserts may be stripped out from final builds.
#define SW_OFFSETOF(_TYPE,_MEMBER)  offsetof(_TYPE, _MEMBER)                    // Offset of _MEMBER within _TYPE. Standardized as offsetof() in C++11
//#define SW_CHECKVERSION()        SW::DebugCheckVersionAndDataLayout(SW_VERSION, sizeof(SwGuiIO), sizeof(SwGuiStyle), sizeof(SwVec2), sizeof(SwVec4), sizeof(SwDrawVert), sizeof(SwDrawIdx))

// Helper Macros - IM_FMTARGS, IM_FMTLIST: Apply printf-style warnings to our formatting functions.
#if !defined(SW_USE_STB_SPRINTF) && defined(__MINGW32__) && !defined(__clang__)
#define SW_FMTARGS(FMT)             __attribute__((format(gnu_printf, FMT, FMT+1)))
#define SW_FMTLIST(FMT)             __attribute__((format(gnu_printf, FMT, 0)))
#elif !defined(SW_USE_STB_SPRINTF) && (defined(__clang__) || defined(__GNUC__))
#define SW_FMTARGS(FMT)             __attribute__((format(printf, FMT, FMT+1)))
#define SW_FMTLIST(FMT)             __attribute__((format(printf, FMT, 0)))
#else
#define SW_FMTARGS(FMT)
#define SW_FMTLIST(FMT)
#endif

// Disable some of MSVC most aggressive Debug runtime checks in function header/footer (used in some simple/low-level functions)
#if defined(_MSC_VER) && !defined(__clang__)  && !defined(__INTEL_COMPILER) && !defined(SW_DEBUG_PARANOID)
#define SW_MSVC_RUNTIME_CHECKS_OFF      __pragma(runtime_checks("",off))     __pragma(check_stack(off)) __pragma(strict_gs_check(push,off))
#define SW_MSVC_RUNTIME_CHECKS_RESTORE  __pragma(runtime_checks("",restore)) __pragma(check_stack())    __pragma(strict_gs_check(pop))
#else
#define SW_MSVC_RUNTIME_CHECKS_OFF
#define SW_MSVC_RUNTIME_CHECKS_RESTORE
#endif

// Warnings
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable: 26495)    // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).
#endif
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wold-style-cast"
#if __has_warning("-Wzero-as-null-pointer-constant")
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
#endif
#elif defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpragmas"          // warning: unknown option after '#pragma GCC diagnostic' kind
#pragma GCC diagnostic ignored "-Wclass-memaccess"  // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
#endif



//-----------------------------------------------------------------------------
// [SECTION] Forward declarations and basic types
//-----------------------------------------------------------------------------

// Forward declarations
struct SwDrawChannel;               // Temporary storage to output draw commands out of order, used by SwDrawListSplitter and SwDrawList::ChannelsSplit()
struct SwDrawCmd;                   // A single draw command within a parent SwDrawList (generally maps to 1 GPU draw call, unless it is a callback)
struct SwDrawData;                  // All draw command lists required to render the frame + pos/size coordinates to use for the projection matrix.
struct SwDrawList;                  // A single draw command list (generally one per window, conceptually you may see this as a dynamic "mesh" builder)
struct SwDrawListSharedData;        // Data shared among multiple draw lists (typically owned by parent SwGui context, but you may create one yourself)
struct SwDrawListSplitter;          // Helper to split a draw list into different layers which can be drawn into out of order, then flattened back.
struct SwDrawVert;                  // A single vertex (pos + uv + col = 20 bytes by default. Override layout with SW_OVERRIDE_DRAWVERT_STRUCT_LAYOUT)
struct SwFont;                      // Runtime data for a single font within a parent SwFontAtlas
struct SwFontAtlas;                 // Runtime data for multiple fonts, bake multiple fonts into a single texture, TTF/OTF font loader
struct SwFontBuilderIO;             // Opaque interface to a font builder (stb_truetype or FreeType).
struct SwFontConfig;                // Configuration data when adding a font or merging fonts
struct SwFontGlyph;                 // A single font glyph (code point + coordinates within in SwFontAtlas + offset)
struct SwFontGlyphRangesBuilder;    // Helper to build glyph ranges from text/string data
struct SwColor;                     // Helper functions to create a color that can be converted to either u32 or float4 (*OBSOLETE* please avoid using)
struct SwTexture;                   // Helper functions to create a texture that can be used by Sw::Image/Sw::ImageButton

struct SwGuiContext;                //  SwGui context (opaque structure, unless including mgui_internal.h)
struct SwGuiIO;                     // Main configuration and I/O between your application and SwGui
struct SwGuiInputTextCallbackData;  // Shared state of InputText() when using custom SwGuiInputTextCallback (rare/advanced use)
struct SwGuiKeyData;                // Storage for SwGuiIO and IsKeyDown(), IsKeyPressed() etc functions.
struct SwGuiListClipper;            // Helper to manually clip large list of items
struct SwGuiOnceUponAFrame;         // Helper for running a block of code not more than once a frame
struct SwGuiPayload;                // User data payload for drag and drop operations
struct SwGuiPlatformIO;             // Multi-viewport support: interface for Platform/Renderer backends + viewports to render
struct SwGuiPlatformMonitor;        // Multi-viewport support: user-provided bounds for each connected monitor/display. Used when positioning popups and tooltips to avoid them straddling monitors
struct SwGuiPlatformImeData;        // Platform IME data for io.SetPlatformSweDataFn() function.
struct SwGuiSizeCallbackData;       // Callback data when using SetNextWindowSizeConstraints() (rare/advanced use)
struct SwGuiStorage;                // Helper for key->value storage
struct SwGuiStyle;                  // Runtime data for styling/colors
struct SwGuiTableSortSpecs;         // Sorting specifications for a table (often handling sort specs for a single column, occasionally more)
struct SwGuiTableColumnSortSpecs;   // Sorting specification for one column of a table
struct SwGuiTextBuffer;             // Helper to hold and append into a text buffer (~string builder)
struct SwGuiTextFilter;             // Helper to parse and apply text filters (e.g. "aaaaa[,bbbbb][,ccccc]")
struct SwGuiViewport;               // A Platform Window (always only one in 'master' branch), in the future may represent Platform Monitor
struct SwGuiWindowClass;            // Window class (rare/advanced uses: provide hints to the platform backend via altered viewport flags and parent/child info)

// Enumerations
// - We don't use strongly typed enums much because they add constraints (can't extend in private code, can't store typed in bit fields, extra casting on iteration)
// - Tip: Use your programming IDE navigation facilities on the names in the _central column_ below to find the actual flags/enum lists!
//   In Visual Studio IDE: CTRL+comma ("Edit.GoToAll") can follow symbols in comments, whereas CTRL+F12 ("Edit.GoToSwplementation") cannot.
//   With Visual Assist installed: ALT+G ("VAssistX.GoToSwplementation") can also follow symbols in comments.
enum SwGuiKey : int;                // -> enum SwGuiKey              // Enum: A key identifier
enum SwGuiMouseSource : int;        // -> enum SwGuiMouseSource      // Enum; A mouse input source identifier (Mouse, TouchScreen, Pen)
typedef int SwGuiCol;               // -> enum SwGuiCol_             // Enum: A color identifier for styling
typedef int SwGuiCond;              // -> enum SwGuiCond_            // Enum: A condition for many Set*() functions
typedef int SwGuiDataType;          // -> enum SwGuiDataType_        // Enum: A primary data type
typedef int SwGuiDir;               // -> enum SwGuiDir_             // Enum: A cardinal direction
typedef int SwGuiMouseButton;       // -> enum SwGuiMouseButton_     // Enum: A mouse button identifier (0=left, 1=right, 2=middle)
typedef int SwGuiMouseCursor;       // -> enum SwGuiMouseCursor_     // Enum: A mouse cursor identifier
typedef int SwGuiSortDirection;     // -> enum SwGuiSortDirection_   // Enum: A sorting direction (ascending or descending)
typedef int SwGuiStyleVar;          // -> enum SwGuiStyleVar_        // Enum: A variable identifier for styling
typedef int SwGuiTableBgTarget;     // -> enum SwGuiTableBgTarget_   // Enum: A color target for TableSetBgColor()

// Flags (declared as int for compatibility with old C++, to allow using as flags without overhead, and to not pollute the top of this file)
// - Tip: Use your programming IDE navigation facilities on the names in the _central column_ below to find the actual flags/enum lists!
//   In Visual Studio IDE: CTRL+comma ("Edit.GoToAll") can follow symbols in comments, whereas CTRL+F12 ("Edit.GoToSwplementation") cannot.
//   With Visual Assist installed: ALT+G ("VAssistX.GoToSwplementation") can also follow symbols in comments.
typedef int SwDrawFlags;            // -> enum SwDrawFlags_          // Flags: for SwDrawList functions
typedef int SwDrawListFlags;        // -> enum SwDrawListFlags_      // Flags: for SwDrawList instance
typedef int SwFontAtlasFlags;       // -> enum SwFontAtlasFlags_     // Flags: for SwFontAtlas build
typedef int SwGuiBackendFlags;      // -> enum SwGuiBackendFlags_    // Flags: for io.BackendFlags
typedef int SwGuiButtonFlags;       // -> enum SwGuiButtonFlags_     // Flags: for InvisibleButton()
typedef int SwGuiChildFlags;        // -> enum SwGuiChildFlags_      // Flags: for BeginChild()
typedef int SwGuiColorEditFlags;    // -> enum SwGuiColorEditFlags_  // Flags: for ColorEdit4(), ColorPicker4() etc.
typedef int SwGuiConfigFlags;       // -> enum SwGuiConfigFlags_     // Flags: for io.ConfigFlags
typedef int SwGuiComboFlags;        // -> enum SwGuiComboFlags_      // Flags: for BeginCombo()
typedef int SwGuiDockNodeFlags;     // -> enum SwGuiDockNodeFlags_   // Flags: for DockSpace()
typedef int SwGuiDragDropFlags;     // -> enum SwGuiDragDropFlags_   // Flags: for BeginDragDropSource(), AcceptDragDropPayload()
typedef int SwGuiFocusedFlags;      // -> enum SwGuiFocusedFlags_    // Flags: for IsWindowFocused()
typedef int SwGuiHoveredFlags;      // -> enum SwGuiHoveredFlags_    // Flags: for IsItemHovered(), IsWindowHovered() etc.
typedef int SwGuiInputTextFlags;    // -> enum SwGuiInputTextFlags_  // Flags: for InputText(), InputTextMultiline()
typedef int SwGuiKeyChord;          // -> SwGuiKey | SwGuiMod_XXX    // Flags: for storage only for now: an SwGuiKey optionally OR-ed with one or more SwGuiMod_XXX values.
typedef int SwGuiModFlags;          // -> enum SwGuiModFlags_        // Flags: for io.KeyMods (Ctrl/Shift/Alt/Super)
typedef int SwGuiPopupFlags;        // -> enum SwGuiPopupFlags_      // Flags: for OpenPopup*(), BeginPopupContext*(), IsPopupOpen()
typedef int SwGuiSelectableFlags;   // -> enum SwGuiSelectableFlags_ // Flags: for Selectable()
typedef int SwGuiSliderFlags;       // -> enum SwGuiSliderFlags_     // Flags: for DragFloat(), DragInt(), SliderFloat(), SliderInt() etc.
typedef int SwGuiTabBarFlags;       // -> enum SwGuiTabBarFlags_     // Flags: for BeginTabBar()
typedef int SwGuiTabItemFlags;      // -> enum SwGuiTabItemFlags_    // Flags: for BeginTabItem()
typedef int SwGuiTableFlags;        // -> enum SwGuiTableFlags_      // Flags: For BeginTable()
typedef int SwGuiTableColumnFlags;  // -> enum SwGuiTableColumnFlags_// Flags: For TableSetupColumn()
typedef int SwGuiTableRowFlags;     // -> enum SwGuiTableRowFlags_   // Flags: For TableNextRow()
typedef int SwGuiTreeNodeFlags;     // -> enum SwGuiTreeNodeFlags_   // Flags: for TreeNode(), TreeNodeEx(), CollapsingHeader()
typedef int SwGuiViewportFlags;     // -> enum SwGuiViewportFlags_   // Flags: for SwGuiViewport
typedef int SwGuiWindowFlags;       // -> enum SwGuiWindowFlags_     // Flags: for Begin(), BeginChild()

// SwTexture: user data for renderer backend to identify a texture [Compile-time configurable type]
// - To use something else than an opaque void* pointer: override with e.g. '#define SwTextureID MyTextureType*' in your imconfig.h file.
// - This can be whatever to you want it to be! read the FAQ about SwTextureID for details.
#ifndef SwTextureID
typedef void* SwTextureID;          // Default: store a pointer or an integer fitting in a pointer (most renderer backends are ok with that)
#endif

// SwDrawIdx: vertex index. [Compile-time configurable type]
// - To use 16-bit indices + allow large meshes: backend need to set 'io.BackendFlags |= SwGuiBackendFlags_RendererHasVtxOffset' and handle SwDrawCmd::VtxOffset (recommended).
// - To use 32-bit indices: override with '#define SwDrawIdx unsigned int' in your imconfig.h file.
#ifndef SwDrawIdx
typedef unsigned short SwDrawIdx;   // Default: 16-bit (for maximum compatibility with renderer backends)
#endif

// Scalar data types
typedef unsigned int        SwGuiID;// A unique ID used by widgets (typically the result of hashing a stack of string)
typedef signed char         SwS8;   // 8-bit signed integer
typedef unsigned char       SwU8;   // 8-bit unsigned integer
typedef signed short        SwS16;  // 16-bit signed integer
typedef unsigned short      SwU16;  // 16-bit unsigned integer
typedef signed int          SwS32;  // 32-bit signed integer == int
typedef unsigned int        SwU32;  // 32-bit unsigned integer (often used to store packed colors)
typedef signed   long long  SwS64;  // 64-bit signed integer
typedef unsigned long long  SwU64;  // 64-bit unsigned integer

// Character types
// (we generally use UTF-8 encoded string in the API. This is storage specifically for a decoded character used for keyboard input and display)
typedef unsigned short SwWchar16;   // A single decoded U16 character/code point. We encode them as multi bytes UTF-8 when used in strings.
typedef unsigned int SwWchar32;     // A single decoded U32 character/code point. We encode them as multi bytes UTF-8 when used in strings.
#ifdef SW_USE_WCHAR32            // SwWchar [configurable type: override in imconfig.h with '#define SW_USE_WCHAR32' to support Unicode planes 1-16]
typedef SwWchar32 SwWchar;
#else
typedef SwWchar16 SwWchar;
#endif


// Callback and functions types
typedef int     (*SwGuiInputTextCallback)(SwGuiInputTextCallbackData* data);    // Callback function for SW::InputText()
typedef void    (*SwGuiSizeCallback)(SwGuiSizeCallbackData* data);              // Callback function for SW::SetNextWindowSizeConstraints()
typedef void*   (*SwGuiMemAllocFunc)(size_t sz, void* user_data);               // Function signature for SW::SetAllocatorFunctions()
typedef void    (*SwGuiMemFreeFunc)(void* ptr, void* user_data);                // Function signature for SW::SetAllocatorFunctions()


// SwVec2: 2D vector used to store positions, sizes etc. [Compile-time configurable type]
// This is a frequently used type in the API. Consider using IM_VEC2_CLASS_EXTRA to create implicit cast from/to our preferred type.
SW_MSVC_RUNTIME_CHECKS_OFF
struct SwVec2
{
    float                                   x, y;
    constexpr SwVec2() : x(0.0f), y(0.0f) { }
    constexpr SwVec2(float _x, float _y) : x(_x), y(_y) { }
    float  operator[] (size_t idx) const { SW_ASSERT(idx <= 1); return (&x)[idx]; }    // We very rarely use this [] operator, the assert overhead is fine.
    float& operator[] (size_t idx) { SW_ASSERT(idx <= 1); return (&x)[idx]; }    // We very rarely use this [] operator, the assert overhead is fine.
#ifdef SW_VEC2_CLASS_EXTRA
    SW_VEC2_CLASS_EXTRA     // Define additional constructors and implicit cast operators in imconfig.h to convert back and forth between your math types and SwVec2.
#endif
};

// SwVec3: 3D vector
struct SwVec3
{
    float                                                     x, y, z;
    constexpr SwVec3() : x(0.0f), y(0.0f), z(0.0f) { }
    constexpr SwVec3(float _x, float _y, float _z) : x(_x), y(_y), z(_z) { }
#ifdef SW_VEC3_CLASS_EXTRA
    SW_VEC3_CLASS_EXTRA     // Define additional constructors and implicit cast operators in imconfig.h to convert back and forth between your math types and SwVec4.
#endif
};

// SwVec4: 4D vector used to store clipping rectangles, colors etc. [Compile-time configurable type]
struct SwVec4
{
    float                                                     x, y, z, w;
    constexpr SwVec4() : x(0.0f), y(0.0f), z(0.0f), w(0.0f) { }
    constexpr SwVec4(float _x, float _y, float _z, float _w) : x(_x), y(_y), z(_z), w(_w) { }
#ifdef SW_VEC4_CLASS_EXTRA
    SW_VEC4_CLASS_EXTRA     // Define additional constructors and implicit cast operators in imconfig.h to convert back and forth between your math types and SwVec4.
#endif
};
SW_MSVC_RUNTIME_CHECKS_RESTORE


//-----------------------------------------------------------------------------
// [SECTION] Helpers: Memory allocations macros, SwVector<>
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// IM_MALLOC(), SW_FREE(), SW_NEW(), SW_PLACEMENT_NEW(), SW_DELETE()
// We call C++ constructor on own allocated memory via the placement "new(ptr) Type()" syntax.
// Defining a custom placement new() with a custom parameter allows us to bypass including <new> which on some platforms complains when user has disabled exceptions.
//-----------------------------------------------------------------------------

struct SwNewWrapper {};
inline void* operator new(size_t, SwNewWrapper, void* ptr) { return ptr; }
inline void  operator delete(void*, SwNewWrapper, void*) {} // This is only required so we can use the symmetrical new()
#define SW_ALLOC(_SIZE)                     SW::MemAlloc(_SIZE)
#define SW_FREE(_PTR)                       SW::MemFree(_PTR)
#define SW_PLACEMENT_NEW(_PTR)              new(SwNewWrapper(), _PTR)
#define SW_NEW(_TYPE)                       new(SwNewWrapper(), SW::MemAlloc(sizeof(_TYPE))) _TYPE
template<typename T> void SW_DELETE(T* p) { if (p) { p->~T(); SW::MemFree(p); } }

//-----------------------------------------------------------------------------
// SwVector<>
// Lightweight std::vector<>-like class to avoid dragging dependencies (also, some implementations of STL with debug enabled are absurdly slow, we bypass it so our code runs fast in debug).
//-----------------------------------------------------------------------------
// - You generally do NOT need to care or use this ever. But we need to make it available in imgui.h because some of our public structures are relying on it.
// - We use std-like naming convention here, which is a little unusual for this codebase.
// - Swportant: clear() frees memory, resize(0) keep the allocated buffer. We use resize(0) a lot to intentionally recycle allocated buffers across frames and amortize our costs.
// - Swportant: our implementation does NOT call C++ constructors/destructors, we treat everything as raw data! This is intentional but be extra mindful of that,
//   Do NOT use this class as a std::vector replacement in your own code! Many of the structures used by  imgui can be safely initialized by a zero-memset.
//-----------------------------------------------------------------------------

SW_MSVC_RUNTIME_CHECKS_OFF
template<typename T>
struct SwVector
{
    int                 Size;
    int                 Capacity;
    T*                  Data;

    // Provide standard typedefs but we don't use them ourselves.
    typedef T                   value_type;
    typedef value_type* iterator;
    typedef const value_type* const_iterator;

    // Constructors, destructor
    inline              SwVector() { Size = Capacity = 0; Data = NULL; }
    inline              SwVector(const SwVector<T>& src) { Size = Capacity = 0; Data = NULL; operator=(src); }
    inline              SwVector<T>& operator=(const SwVector<T>& src) { clear(); resize(src.Size); if (src.Data) memcpy(Data, src.Data, (size_t)Size * sizeof(T)); return *this; }
    inline              ~SwVector() { if (Data) SW_FREE(Data); } // Swportant: does not destruct anything

    inline void         clear() { if (Data) { Size = Capacity = 0; SW_FREE(Data); Data = NULL; } }  // Swportant: does not destruct anything
    inline void         clear_delete() { for (int n = 0; n < Size; n++) SW_DELETE(Data[n]); clear(); }     // Swportant: never called automatically! always explicit.
    inline void         clear_destruct() { for (int n = 0; n < Size; n++) Data[n].~T(); clear(); }           // Swportant: never called automatically! always explicit.

    inline bool         empty() const { return Size == 0; }
    inline int          size() const { return Size; }
    inline int          size_in_bytes() const { return Size * (int)sizeof(T); }
    inline int          max_size() const { return 0x7FFFFFFF / (int)sizeof(T); }
    inline int          capacity() const { return Capacity; }
    inline T& operator[](int i) { SW_ASSERT(i >= 0 && i < Size); return Data[i]; }
    inline const T& operator[](int i) const { SW_ASSERT(i >= 0 && i < Size); return Data[i]; }

    inline T*           begin() { return Data; }
    inline const T*     begin() const { return Data; }
    inline T*           end() { return Data + Size; }
    inline const T*     end() const { return Data + Size; }
    inline T&           front() { SW_ASSERT(Size > 0); return Data[0]; }
    inline const T&     front() const { SW_ASSERT(Size > 0); return Data[0]; }
    inline T&           back() { SW_ASSERT(Size > 0); return Data[Size - 1]; }
    inline const T&     back() const { SW_ASSERT(Size > 0); return Data[Size - 1]; }
    inline void         swap(SwVector<T>& rhs) { int rhs_size = rhs.Size; rhs.Size = Size; Size = rhs_size; int rhs_cap = rhs.Capacity; rhs.Capacity = Capacity; Capacity = rhs_cap; T* rhs_data = rhs.Data; rhs.Data = Data; Data = rhs_data; }

    inline int          _grow_capacity(int sz) const { int new_capacity = Capacity ? (Capacity + Capacity / 2) : 8; return new_capacity > sz ? new_capacity : sz; }
    inline void         resize(int new_size) { if (new_size > Capacity) reserve(_grow_capacity(new_size)); Size = new_size; }
    inline void         resize(int new_size, const T& v) { if (new_size > Capacity) reserve(_grow_capacity(new_size)); if (new_size > Size) for (int n = Size; n < new_size; n++) memcpy(&Data[n], &v, sizeof(v)); Size = new_size; }
    inline void         shrink(int new_size) { SW_ASSERT(new_size <= Size); Size = new_size; } // Resize a vector to a smaller size, guaranteed not to cause a reallocation
    inline void         reserve(int new_capacity) { if (new_capacity <= Capacity) return; T* new_data = (T*)SW_ALLOC((size_t)new_capacity * sizeof(T)); if (Data) { memcpy(new_data, Data, (size_t)Size * sizeof(T)); SW_FREE(Data); } Data = new_data; Capacity = new_capacity; }
    inline void         reserve_discard(int new_capacity) { if (new_capacity <= Capacity) return; if (Data) SW_FREE(Data); Data = (T*)SW_ALLOC((size_t)new_capacity * sizeof(T)); Capacity = new_capacity; }

    // NB: It is illegal to call push_back/push_front/insert with a reference pointing inside the SwVector data itself! e.g. v.push_back(v[10]) is forbidden.
    inline void         push_back(const T& v) { if (Size == Capacity) reserve(_grow_capacity(Size + 1)); memcpy(&Data[Size], &v, sizeof(v)); Size++; }
    inline void         pop_back() { SW_ASSERT(Size > 0); Size--; }
    inline void         push_front(const T& v) { if (Size == 0) push_back(v); else insert(Data, v); }
    inline T*           erase(const T* it) { SW_ASSERT(it >= Data && it < Data + Size); const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + 1, ((size_t)Size - (size_t)off - 1) * sizeof(T)); Size--; return Data + off; }
    inline T*           erase(const T* it, const T* it_last) { SW_ASSERT(it >= Data && it < Data + Size && it_last >= it && it_last <= Data + Size); const ptrdiff_t count = it_last - it; const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + count, ((size_t)Size - (size_t)off - (size_t)count) * sizeof(T)); Size -= (int)count; return Data + off; }
    inline T*           erase_unsorted(const T* it) { SW_ASSERT(it >= Data && it < Data + Size);  const ptrdiff_t off = it - Data; if (it < Data + Size - 1) memcpy(Data + off, Data + Size - 1, sizeof(T)); Size--; return Data + off; }
    inline T*           insert(const T* it, const T& v) { SW_ASSERT(it >= Data && it <= Data + Size); const ptrdiff_t off = it - Data; if (Size == Capacity) reserve(_grow_capacity(Size + 1)); if (off < (int)Size) memmove(Data + off + 1, Data + off, ((size_t)Size - (size_t)off) * sizeof(T)); memcpy(&Data[off], &v, sizeof(v)); Size++; return Data + off; }
    inline bool         contains(const T& v) const { const T* data = Data;  const T* data_end = Data + Size; while (data < data_end) if (*data++ == v) return true; return false; }
    inline T*           find(const T& v) { T* data = Data;  const T* data_end = Data + Size; while (data < data_end) if (*data == v) break; else ++data; return data; }
    inline const T*     find(const T& v) const { const T* data = Data;  const T* data_end = Data + Size; while (data < data_end) if (*data == v) break; else ++data; return data; }
    inline bool         find_erase(const T& v) { const T* it = find(v); if (it < Data + Size) { erase(it); return true; } return false; }
    inline bool         find_erase_unsorted(const T& v) { const T* it = find(v); if (it < Data + Size) { erase_unsorted(it); return true; } return false; }
    inline int          index_from_ptr(const T* it) const { SW_ASSERT(it >= Data && it < Data + Size); const ptrdiff_t off = it - Data; return (int)off; }
};
SW_MSVC_RUNTIME_CHECKS_RESTORE

//-----------------------------------------------------------------------------
// [SECTION]  SwGui end-user API functions
// (Note that SW:: being a namespace, you can add extra SW:: functions in your own separate file. Please don't modify SwGui source files!)
//-----------------------------------------------------------------------------

namespace SW
{
    // Context creation and access
    // - Each context create its own SwFontAtlas by default. You may instance one yourself and pass it to CreateContext() to share a font atlas between contexts.
    // - DLL users: heaps and globals are not shared across DLL boundaries! You will need to call SetCurrentContext() + SetAllocatorFunctions()
    //   for each static/DLL boundary you are calling from. Read "Context and Memory Allocators" section of imgui.cpp for details.
    SW_API SwGuiContext*		  CreateContext(SwFontAtlas* shared_font_atlas = NULL);
    SW_API void                   DestroyContext(SwGuiContext* ctx = NULL);   // NULL = destroy current context
    SW_API SwGuiContext*		  GetCurrentContext();
    SW_API void				      SetCurrentContext(SwGuiContext* ctx);


    // Main
    SW_API SwGuiIO&               GetIO();                                                            // access the IO structure (mouse/keyboard/gamepad inputs, time, various configuration options/flags)
    SW_API SwGuiStyle&            GetStyle();                                                         // access the Style structure (colors, sizes). Always use PushStyleCol(), PushStyleVar() to modify style mid-frame!
    SW_API void                   NewFrame();                                                         // start a new  SwGui frame, you can submit any command from this point until Render()/EndFrame().
    SW_API void                   EndFrame();                                                         // ends the  SwGui frame. automatically called by Render(). If you don't need to render data (skipping rendering) you may call EndFrame() without Render()... but you'll have wasted CPU already! If you don't need to render, better to not create any windows and not call NewFrame() at all!
    SW_API void                   Render();                                                           // ends the  SwGui frame, finalize the draw data. You can then get call GetDrawData().
    SW_API SwDrawData*            GetDrawData();                                                      // valid after Render() and until the next call to NewFrame(). this is what you have to render.


    // Windows
    // - Begin() = push window to the stack and start appending to it. End() = pop window from the stack.
    // - Passing 'bool* p_open != NULL' shows a window-closing widget in the upper-right corner of the window,
    //   which clicking will set the boolean to false when clicked.
    // - You may append multiple times to the same window during the same frame by calling Begin()/End() pairs multiple times.
    //   Some information such as 'flags' or 'p_open' will only be considered by the first call to Begin().
    // - Begin() return false to indicate the window is collapsed or fully clipped, so you may early out and omit submitting
    //   anything to the window. Always call a matching End() for each Begin() call, regardless of its return value!
    //   [Important: due to legacy reason, this is inconsistent with most other functions such as BeginMenu/EndMenu,
    //    BeginPopup/EndPopup, etc. where the EndXXX call should only be called if the corresponding BeginXXX function
    //    returned true. Begin and BeginChild are the only odd ones out. Will be fixed in a future update.]
    // - Note that the bottom of window stack always contains a window called "Debug".
    SW_API bool                   Begin(const char* name, bool* p_open = NULL, SwGuiWindowFlags flags = 0);
    SW_API void                   End();


    // Child Windows
    // - Use child windows to begin into a self-contained independent scrolling/clipping regions within a host window. Child windows can embed their own child.
    // - Manual sizing (each axis can use a different setting e.g. SwVec2(0.0f, 400.0f)):
    //     == 0.0f: use remaining parent window size for this axis.
    //      > 0.0f: use specified size for this axis.
    //      < 0.0f: right/bottom-align to specified distance from available content boundaries.
    // - Specifying SwGuiChildFlags_AutoResizeX or SwGuiChildFlags_AutoResizeY makes the sizing automatic based on child contents.
    //   Combining both SwGuiChildFlags_AutoResizeX _and_ SwGuiChildFlags_AutoResizeY defeats purpose of a scrolling region and is NOT recommended.
    // - BeginChild() returns false to indicate the window is collapsed or fully clipped, so you may early out and omit submitting
    //   anything to the window. Always call a matching EndChild() for each BeginChild() call, regardless of its return value.
    //   [Important: due to legacy reason, Begin/End and BeginChild/EndChild are inconsistent with all other functions
    //    such as BeginMenu/EndMenu, BeginPopup/EndPopup, etc. where the EndXXX call should only be called if the corresponding
    //    BeginXXX function returned true. Begin and BeginChild are the only odd ones out. Will be fixed in a future update.]
    SW_API bool                   BeginChild(const char* str_id, const SwVec2& size = SwVec2(0, 0), SwGuiChildFlags child_flags = 0, SwGuiWindowFlags window_flags = 0);
    SW_API bool                   BeginChild(SwGuiID id, const SwVec2& size = SwVec2(0, 0), SwGuiChildFlags child_flags = 0, SwGuiWindowFlags window_flags = 0);
    SW_API void                   EndChild();

    // Windows Utilities
    // - 'current window' = the window we are appending into while inside a Begin()/End() block. 'next window' = next window we will Begin() into.
    SW_API bool                   IsWindowAppearing();
    SW_API bool                   IsWindowCollapsed();
    SW_API bool                   IsWindowFocused(SwGuiFocusedFlags flags = 0); // is current window focused? or its root/child, depending on flags. see flags for options.
    SW_API bool                   IsWindowHovered(SwGuiHoveredFlags flags = 0); // is current window hovered (and typically: not blocked by a popup/modal)? see flags for options. NB: If you are trying to check whether your mouse should be dispatched to imgui or to your app, you should use the 'io.WantCaptureMouse' boolean for that! Please read the FAQ!
    SW_API SwDrawList*            GetWindowDrawList();                        // get draw list associated to the current window, to append your own drawing primitives
    SW_API float                  GetWindowDpiScale();                        // get DPI scale currently associated to the current window's viewport.
    SW_API SwVec2                 GetWindowPos();                             // get current window position in screen space (useful if you want to do your own drawing via the DrawList API)
    SW_API SwVec2                 GetWindowSize();                            // get current window size
    SW_API float                  GetWindowWidth();                           // get current window width (shortcut for GetWindowSize().x)
    SW_API float                  GetWindowHeight();                          // get current window height (shortcut for GetWindowSize().y)
    SW_API SwGuiViewport*         GetWindowViewport();                        // get viewport currently associated to the current window.

    // Window manipulation
    // - Prefer using SetNextXXX functions (before Begin) rather that SetXXX functions (after Begin).
    SW_API void                   SetNextWindowPos(const SwVec2& pos, SwGuiCond cond = 0, const SwVec2& pivot = SwVec2(0, 0)); // set next window position. call before Begin(). use pivot=(0.5f,0.5f) to center on given point, etc.
    SW_API void                   SetNextWindowSize(const SwVec2& size, SwGuiCond cond = 0);                  // set next window size. set axis to 0.0f to force an auto-fit on this axis. call before Begin()
    SW_API void                   SetNextWindowSizeConstraints(const SwVec2& size_min, const SwVec2& size_max, SwGuiSizeCallback custom_callback = NULL, void* custom_callback_data = NULL); // set next window size limits. use -1,-1 on either X/Y axis to preserve the current size. Sizes will be rounded down. Use callback to apply non-trivial programmatic constraints.
    SW_API void                   SetNextWindowContentSize(const SwVec2& size);                               // set next window content size (~ scrollable client area, which enforce the range of scrollbars). Not including window decorations (title bar, menu bar, etc.) nor WindowPadding. set an axis to 0.0f to leave it automatic. call before Begin()
    SW_API void                   SetNextWindowCollapsed(bool collapsed, SwGuiCond cond = 0);                 // set next window collapsed state. call before Begin()
    SW_API void                   SetNextWindowFocus();                                                       // set next window to be focused / top-most. call before Begin()
    SW_API void                   SetNextWindowBgAlpha(float alpha);                                          // set next window background color alpha. helper to easily override the Alpha component of SwGuiCol_WindowBg/ChildBg/PopupBg. you may also use SwGuiWindowFlags_NoBackground.
    SW_API void                   SetNextWindowViewport(SwGuiID viewport_id);                                 // set next window viewport
    SW_API void                   SetWindowPos(const SwVec2& pos, SwGuiCond cond = 0);                        // (not recommended) set current window position - call within Begin()/End(). prefer using SetNextWindowPos(), as this may incur tearing and side-effects.
    SW_API void                   SetWindowSize(const SwVec2& size, SwGuiCond cond = 0);                      // (not recommended) set current window size - call within Begin()/End(). set to SwVec2(0, 0) to force an auto-fit. prefer using SetNextWindowSize(), as this may incur tearing and minor side-effects.
    SW_API void                   SetWindowCollapsed(bool collapsed, SwGuiCond cond = 0);                     // (not recommended) set current window collapsed state. prefer using SetNextWindowCollapsed().
    SW_API void                   SetWindowFocus();                                                           // (not recommended) set current window to be focused / top-most. prefer using SetNextWindowFocus().
    SW_API void                   SetWindowFontScale(float scale);                                            // [OBSOLETE] set font scale. Adjust IO.FontGlobalScale if you want to scale all windows. This is an old API! For correct scaling, prefer to reload font + rebuild SwFontAtlas + call style.ScaleAllSizes().
    SW_API void                   SetWindowPos(const char* name, const SwVec2& pos, SwGuiCond cond = 0);      // set named window position.
    SW_API void                   SetWindowSize(const char* name, const SwVec2& size, SwGuiCond cond = 0);    // set named window size. set axis to 0.0f to force an auto-fit on this axis.
    SW_API void                   SetWindowCollapsed(const char* name, bool collapsed, SwGuiCond cond = 0);   // set named window collapsed state
    SW_API void                   SetWindowFocus(const char* name);                                           // set named window to be focused / top-most. use NULL to remove focus. to 0.0f to force an auto-fit on this axis. call before Begin()


    // Windows Scrolling
    SW_API float                  GetScrollX();                                                   // get scrolling amount [0 .. GetScrollMaxX()]
    SW_API float                  GetScrollY();                                                   // get scrolling amount [0 .. GetScrollMaxY()]
    SW_API void                   SetScrollX(float scroll_x);                                     // set scrolling amount [0 .. GetScrollMaxX()]
    SW_API void                   SetScrollY(float scroll_y);                                     // set scrolling amount [0 .. GetScrollMaxY()]
    SW_API float                  GetScrollMaxX();                                                // get maximum scrolling amount ~~ ContentSize.x - WindowSize.x - DecorationsSize.x
    SW_API float                  GetScrollMaxY();                                                // get maximum scrolling amount ~~ ContentSize.y - WindowSize.y - DecorationsSize.y
    SW_API void                   SetScrollHereX(float center_x_ratio = 0.5f);                    // adjust scrolling amount to make current cursor position visible. center_x_ratio=0.0: left, 0.5: center, 1.0: right. When using to make a "default/current item" visible, consider using SetItemDefaultFocus() instead.
    SW_API void                   SetScrollHereY(float center_y_ratio = 0.5f);                    // adjust scrolling amount to make current cursor position visible. center_y_ratio=0.0: top, 0.5: center, 1.0: bottom. When using to make a "default/current item" visible, consider using SetItemDefaultFocus() instead.
    SW_API void                   SetScrollFromPosX(float local_x, float center_x_ratio = 0.5f);  // adjust scrolling amount to make given position visible. Generally GetCursorStartPos() + offset to compute a valid position.
    SW_API void                   SetScrollFromPosY(float local_y, float center_y_ratio = 0.5f);  // adjust scrolling amount to make given position visible. Generally GetCursorStartPos() + offset to compute a valid position.

    // Styles
    SW_API void                   StyleColorsDark(SwGuiStyle* dst = NULL);                          // new, recommended style (default)
    SW_API void                   StyleColorsLight(SwGuiStyle* dst = NULL);                         // best used with borders and a custom, thicker font
    SW_API void                   StyleColorsClassic(SwGuiStyle* dst = NULL);                       // classic imgui style


    // Parameters stacks (current window)
    SW_API void                   PushItemWidth(float item_width);                                    // push width of items for common large "item+label" widgets. >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -FLT_MIN always align width to the right side).
    SW_API void                   PopItemWidth();
    SW_API void                   SetNextItemWidth(float item_width);                                 // set width of the _next_ common large "item+label" widget. >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -FLT_MIN always align width to the right side)
    SW_API float                  CalcItemWidth();                                                    // width of item given pushed settings and current cursor position. NOT necessarily the width of last item unlike most 'Item' functions.
    SW_API void                   PushTextWrapPos(float wrap_local_pos_x = 0.0f);                     // push word-wrapping position for Text*() commands. < 0.0f: no wrapping; 0.0f: wrap to end of window (or column); > 0.0f: wrap at 'wrap_pos_x' position in window local space
    SW_API void                   PopTextWrapPos();


    // Viewports
    // - Currently represents the Platform Window created by the application which is hosting our  SwGui windows.
    // - In 'docking' branch with multi-viewport enabled, we extend this concept to have multiple active viewports.
    // - In the future we will extend this concept further to also represent Platform Monitor and support a "no main platform window" operation mode.
    SW_API SwGuiViewport*         GetMainViewport();


    // Background/Foreground Draw Lists
    SW_API SwDrawList*            GetBackgroundDrawList();                                            // this draw list will be the first rendered one. Useful to quickly draw shapes/text behind  imgui contents.
    SW_API SwDrawList*            GetForegroundDrawList();                                            // this draw list will be the last rendered one. Useful to quickly draw shapes/text over  imgui contents.


    // Miscellaneous Utilities
    SW_API int                    GetFrameCount();                                                    // get global imgui frame count. incremented by 1 every frame.


    // Memory Allocators
    // - Those functions are not reliant on the current context.
    // - DLL users: heaps and globals are not shared across DLL boundaries! You will need to call SetCurrentContext() + SetAllocatorFunctions()
    //   for each static/DLL boundary you are calling from. Read "Context and Memory Allocators" section of imgui.cpp for more details.
    SW_API void                   SetAllocatorFunctions(SwGuiMemAllocFunc alloc_func, SwGuiMemFreeFunc free_func, void* user_data = NULL);
    SW_API void                   GetAllocatorFunctions(SwGuiMemAllocFunc* p_alloc_func, SwGuiMemFreeFunc* p_free_func, void** p_user_data);
    SW_API void*                  MemAlloc(size_t size);
    SW_API void                   MemFree(void* ptr);


    // (Optional) Platform/OS interface for multi-viewport support
    // Read comments around the SwGuiPlatformIO structure for more details.
    // Note: You may use GetWindowViewport() to get the current viewport of the current window.
    SW_API void                   UpdatePlatformWindows();                                        // call in main loop. will call CreateWindow/ResizeWindow/etc. platform functions for each secondary viewport, and DestroyWindow for each inactive viewport.
    SW_API SwGuiPlatformIO&       GetPlatformIO();
    SW_API void                   RenderPlatformWindowsDefault(void* platform_render_arg = NULL, void* renderer_render_arg = NULL); // call in main loop. will call RenderWindow/SwapBuffers platform functions for each secondary viewport which doesn't have the SwGuiViewportFlags_IsSwmized flag set. May be reimplemented by user for custom rendering needs.
    SW_API void                   DestroyPlatformWindows();                                       // call DestroyWindow platform functions for all viewports. call from backend Shutdown() if you need to close platform windows before imgui shutdown. otherwise will be called by DestroyContext().
    SW_API SwGuiViewport*         FindViewportByID(SwGuiID id);                                   // this is a helper for backends.
    SW_API SwGuiViewport*         FindViewportByPlatformHandle(void* platform_handle);            // this is a helper for backends. the type platform_handle is decided by the backend (e.g. HWND, MyWindow*, GLFWwindow* etc.)


    // Inputs Utilities: Mouse
    // - To refer to a mouse button, you may use named enums in your code e.g. SwGuiMouseButton_Left, SwGuiMouseButton_Right.
    // - You can also use regular integer: it is forever guaranteed that 0=Left, 1=Right, 2=Middle.
    // - Dragging operations are only reported after mouse has moved a certain distance away from the initial clicking position (see 'lock_threshold' and 'io.MouseDraggingThreshold')
    SW_API bool                   IsMouseClicked(SwGuiMouseButton button, bool repeat = false);     // did mouse button clicked? (went from !Down to Down). Same as GetMouseClickedCount() == 1.
    SW_API bool                   IsMouseReleased(SwGuiMouseButton button);                           // did mouse button released? (went from Down to !Down)
    SW_API bool                   IsMouseDoubleClicked(SwGuiMouseButton button);                      // did mouse button double-clicked? Same as GetMouseClickedCount() == 2. (note that a double-click will also report IsMouseClicked() == true)
    SW_API bool                   IsMouseHoveringRect(const SwVec2& r_min, const SwVec2& r_max, bool clip = true);// is mouse hovering given bounding rect (in screen space). clipped by current clipping settings, but disregarding of other consideration of focus/window ordering/popup-block.
    SW_API bool                   IsMousePosValid(const SwVec2* mouse_pos = NULL);                  // by convention we use (-FLT_MAX,-FLT_MAX) to denote that there is no mouse available
    SW_API bool                   IsMouseDown(SwGuiMouseButton button);                               // is mouse button held?
    SW_API bool                   IsMouseDragging(SwGuiMouseButton button, float lock_threshold = -1.0f);// is mouse dragging? (if lock_threshold < -1.0f, uses io.MouseDraggingThreshold)
    SW_API SwGuiMouseCursor       GetMouseCursor();                                                // get desired cursor type, reset in SW::NewFrame(), this is updated during the frame. valid before Render(). If you use software rendering by setting io.MouseDrawCursor SwGui will render those for you
    SW_API void                   SetMouseCursor(SwGuiMouseCursor cursor_type);                       // set desired cursor type
    SW_API bool                   IsAnyMouseDown();                                                   // [WILL OBSOLETE] is any mouse button held? This was designed for backends, but prefer having backend maintain a mask of held mouse buttons, because upcoming input queue system will make this invalid.
    SW_API SwVec2                 GetMousePos();

    // Clipboard Utilities
    // - Also see the LogToClipboard() function to capture GUI into clipboard, or easily output text data to the clipboard.
    SW_API const char*            GetClipboardText();
    SW_API void                   SetClipboardText(const char* text);

     // Color Utilities
    SW_API SwVec4                 ColorConvertU32ToFloat4(SwU32 in);
    SW_API SwU32                  ColorConvertFloat4ToU32(const SwVec4& in);
    SW_API void                   ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v);
    SW_API void                   ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b);


    // Inputs Utilities: Keyboard
    // Without SW_DISABLE_OBSOLETE_KEYIO: (legacy support)
    //   - For 'SwGuiKey key' you can still use your legacy native/user indices according to how your backend/engine stored them in io.KeysDown[].
    // With SW_DISABLE_OBSOLETE_KEYIO: (this is the way forward)
    //   - Any use of 'SwGuiKey' will assert when key < 512 will be passed, previously reserved as native/user keys indices
    //   - GetKeyIndex() is pass-through and therefore deprecated (gone if SW_DISABLE_OBSOLETE_KEYIO is defined)
    SW_API bool                   IsKeyDown(SwGuiKey key);                                            // is key being held.
    SW_API bool                   IsKeyPressed(SwGuiKey key, bool repeat = true);                     // was key pressed (went from !Down to Down)? if repeat=true, uses io.KeyRepeatDelay / KeyRepeatRate
    SW_API bool                   IsKeyChordPressed(SwGuiKeyChord key_chord);                         // was key chord (mods + key) pressed, e.g. you can pass 'SwGuiMod_Ctrl | SwGuiKey_S' as a key-chord. This doesn't do any routing or focus check, please consider using Shortcut() function instead.
    SW_API bool                   IsKeyReleased(SwGuiKey key);                                        // was key released (went from Down to !Down)?
    SW_API int                    GetKeyPressedAmount(SwGuiKey key, float repeat_delay, float rate);  // uses provided repeat rate/delay. return a count, most often 0 or 1 but might be >1 if RepeatRate is small enough that DeltaTime > RepeatRate
    SW_API const char*            GetKeyName(SwGuiKey key);                                           // [DEBUG] returns English name of the key. Those names a provided for debugging purpose and are not meant to be saved persistently not compared.
    //SW_API void                   SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard);        // Override io.WantCaptureKeyboard flag next frame (said flag is left for your application to handle, typically when true it instructs your app to ignore inputs). e.g. force capture keyboard when your widget is being hovered. This is equivalent to setting "io.WantCaptureKeyboard = want_capture_keyboard"; after the next NewFrame() call.

	// Legacy Columns API (2020: prefer using Tables!)
	// - You can also use SameLine(pos_x) to mimic simplified columns.
	//SW_API void                   Columns(int count = 1, const char* id = NULL, bool border = true);
	//SW_API void                   NextColumn();                                                       // next column, defaults to current row or next row if the current row is finished
	//SW_API int                    GetColumnIndex();                                                   // get current column index
	SW_API float                  GetColumnWidth(int column_index = -1);                              // get column width (in pixels). pass -1 to use current column
	SW_API void                   SetColumnWidth(int column_index, float width);                      // set column width (in pixels). pass -1 to use current column
	SW_API float                  GetColumnOffset(int column_index = -1);                             // get position of column line (in pixels, from the left side of the contents region). pass -1 to use current column, otherwise 0..GetColumnsCount() inclusive. column 0 is typically 0.0f
	SW_API void                   SetColumnOffset(int column_index, float offset_x);                  // set position of column line (in pixels, from the left side of the contents region). pass -1 to use current column
	//SW_API int                    GetColumnsCount();


	// Content region
	// - Retrieve available space from a given point. GetContentRegionAvail() is frequently useful.
	// - Those functions are bound to be redesigned (they are confusing, incomplete and the Min/Max return values are in local window coordinates which increases confusion)
    SW_API SwVec2                 GetContentRegionAvail();


    // Disabling [BETA API]
    // - Disable all user interactions and dim items visuals (applying style.DisabledAlpha over current colors)
    // - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled)
    // - BeginDisabled(false) essentially does nothing useful but is provided to facilitate use of boolean expressions. If you can avoid calling BeginDisabled(False)/EndDisabled() best to avoid it.
    SW_API void                   BeginDisabled(bool disabled = true);
    SW_API void                   EndDisabled();


	// Clipping
	// - Mouse hovering is affected by SW::PushClipRect() calls, unlike direct calls to SwDrawList::PushClipRect() which are render only.
    SW_API void                   PushClipRect(const SwVec2& clip_rect_min, const SwVec2& clip_rect_max, bool intersect_with_current_clip_rect);
    SW_API void                   PopClipRect();


    // Focus, Activation
    // - Prefer using "SetItemDefaultFocus()" over "if (IsWindowAppearing()) SetScrollHereY()" when applicable to signify "this is the default item"
    SW_API void                   SetItemDefaultFocus();                                              // make last item the default focused item of a window.

    // Parameters stacks (shared)
    SW_API void                   PushFont(SwFont* font);                                           // use NULL as a shortcut to push default font
    SW_API void                   PopFont();
    SW_API void                   PushStyleColor(SwGuiCol idx, SwU32 col);                        // modify a style color. always use this if you modify the style after NewFrame().
    SW_API void                   PushStyleColor(SwGuiCol idx, const SwVec4& col);
    SW_API void                   PopStyleColor(int count = 1);
    SW_API void                   PushStyleVar(SwGuiStyleVar idx, float val);                       // modify a style float variable. always use this if you modify the style after NewFrame().
    SW_API void                   PushStyleVar(SwGuiStyleVar idx, const SwVec2& val);             // modify a style SwVec2 variable. always use this if you modify the style after NewFrame().
    SW_API void                   PopStyleVar(int count = 1);
    SW_API void                   PushAllowKeyboardFocus(bool allow_keyboard_focus);                  // == tab stop enable. Allow focusing using TAB/Shift-TAB, enabled by default but you can disable it for certain widgets
    SW_API void                   PopAllowKeyboardFocus();
    SW_API void                   PushButtonRepeat(bool repeat);                                      // in 'repeat' mode, Button*() functions return repeated true in a typematic manner (using io.KeyRepeatDelay/io.KeyRepeatRate setting). Note that you can call IsItemActive() after any Button() to tell if the button is held in the current frame.
    SW_API void                   PopButtonRepeat();
    SW_API SwVec2                 GetFontTexUvWhitePixel();                                           // get UV coordinate for a while pixel, useful to draw custom shapes via the SwDrawList API


    // Style read access
    // - Use the style editor (ShowStyleEditor() function) to interactively see what the colors are)
    SW_API SwU32                  GetColorU32(SwGuiCol idx, float alpha_mul = 1.0f);              // retrieve given style color with style alpha applied and optional extra alpha multiplier, packed as a 32-bit value suitable for SwDrawList
    SW_API SwU32                  GetColorU32(const SwVec4& col);                                 // retrieve given color with style alpha applied, packed as a 32-bit value suitable for SwDrawList
    SW_API SwU32                  GetColorU32(SwU32 col);                                         // retrieve given color with style alpha applied, packed as a 32-bit value suitable for SwDrawList


    // Cursor / Layout
    // - By "cursor" we mean the current output position.
    // - The typical widget behavior is to output themselves at the current cursor position, then move the cursor one line down.
    // - You can call SameLine() between widgets to undo the last carriage return and output at the right of the preceding widget.
    // - Attention! We currently have inconsistencies between window-local and absolute positions we will aim to fix with future API:
    //    Window-local coordinates:   SameLine(), GetCursorPos(), SetCursorPos(), GetCursorStartPos(), GetContentRegionMax(), GetWindowContentRegion*(), PushTextWrapPos()
    //    Absolute coordinate:        GetCursorScreenPos(), SetCursorScreenPos(), all SwDrawList:: functions.   
    SW_API void                   Separator();                                                    // separator, generally horizontal. inside a menu bar or in horizontal layout mode, this becomes a vertical separator.
    SW_API void                   SameLine(float offset_from_start_x = 0.0f, float spacing = -1.0f);  // call between widgets or groups to layout them horizontally. X position given in window coordinates.
    SW_API void                   NewLine();                                                      // undo a SameLine() or force a new line when in a horizontal-layout context.
    SW_API void                   Spacing();                                                      // add vertical spacing.
    SW_API void                   Dummy(const SwVec2& size);                                      // add a dummy item of given size. unlike InvisibleButton(), Dummy() won't take the mouse click or be navigable into.
    SW_API void                   Indent(float indent_w = 0.0f);                                  // move content position toward the right, by indent_w, or style.IndentSpacing if indent_w <= 0
    SW_API void                   Unindent(float indent_w = 0.0f);                                // move content position back to the left, by indent_w, or style.IndentSpacing if indent_w <= 0
    SW_API void                   BeginGroup();                                                   // lock horizontal starting position
    SW_API void                   EndGroup();                                                     // unlock horizontal starting position + capture the whole group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
    SW_API SwVec2                 GetCursorPos();                                                 // cursor position in window coordinates (relative to window position)
    SW_API float                  GetCursorPosX();                                                //   (some functions are using window-relative coordinates, such as: GetCursorPos, GetCursorStartPos, GetContentRegionMax, GetWindowContentRegion* etc.
    SW_API float                  GetCursorPosY();                                                //    other functions such as GetCursorScreenPos or everything in SwDrawList::
    SW_API void                   SetCursorPos(const SwVec2& local_pos);                          //    are using the main, absolute coordinate system.
    SW_API void                   SetCursorPosX(float local_x);                                   //    GetWindowPos() + GetCursorPos() == GetCursorScreenPos() etc.)
    SW_API void                   SetCursorPosY(float local_y);                                   //
    SW_API SwVec2                 GetCursorStartPos();                                            // initial cursor position in window coordinates
    SW_API SwVec2                 GetCursorScreenPos();                                           // cursor position in absolute coordinates (useful to work with SwDrawList API). generally top-left == GetMainViewport()->Pos == (0,0) in single viewport mode, and bottom-right == GetMainViewport()->Pos+Size == io.DisplaySize in single-viewport mode.
    SW_API void                   SetCursorScreenPos(const SwVec2& pos);                          // cursor position in absolute coordinates
    SW_API void                   AlignTextToFramePadding();                                      // vertically align upcoming text baseline to FramePadding.y so that it will align properly to regularly framed items (call if you have text on a line before a framed item)
    SW_API float                  GetTextLineHeight();                                            // ~ FontSize
    SW_API float                  GetTextLineHeightWithSpacing();                                 // ~ FontSize + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of text)
    SW_API float                  GetFrameHeight();                                               // ~ FontSize + style.FramePadding.y * 2
    SW_API float                  GetFrameHeightWithSpacing();                                    // ~ FontSize + style.FramePadding.y * 2 + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of framed widgets)

    // ID stack/scopes
    // Read the FAQ (docs/FAQ.md or http://imgui.org/faq) for more details about how ID are handled in  imgui.
    // - Those questions are answered and impacted by understanding of the ID stack system:
    //   - "Q: Why is my widget not reacting when I click on it?"
    //   - "Q: How can I have widgets with an empty label?"
    //   - "Q: How can I have multiple widgets with the same label?"
    // - Short version: ID are hashes of the entire ID stack. If you are creating widgets in a loop you most likely
    //   want to push a unique identifier (e.g. object pointer, loop index) to uniquely differentiate them.
    // - You can also use the "Label##foobar" syntax within widget label to distinguish them from each others.
    // - In this header file we use the "label"/"name" terminology to denote a string that will be displayed + used as an ID,
    //   whereas "str_id" denote a string that is only used as an ID and not normally displayed.
    SW_API void                   PushID(const char* str_id);                                          // push string into the ID stack (will hash string).
    SW_API void                   PushID(const char* str_id_begin, const char* str_id_end);            // push string into the ID stack (will hash string).
    SW_API void                   PushID(const void* ptr_id);                                          // push pointer into the ID stack (will hash pointer).
    SW_API void                   PushID(int int_id);                                                  // push integer into the ID stack (will hash integer).
    SW_API void                   PopID();                                                             // pop from the ID stack.
    SW_API SwGuiID                GetID(const char* str_id);                                           // calculate unique ID (hash of whole ID stack + given parameter). e.g. if you want to query into SwGuiStorage yourself
    SW_API SwGuiID                GetID(const char* str_id_begin, const char* str_id_end);
    SW_API SwGuiID                GetID(const void* ptr_id);


    // 2D graphics
    SW_API void                   Line(const SwVec2& p1, const SwVec2& p2, SwU32 col, float thickness = 1.0f);
    SW_API void                   Rect(const SwVec2& p_min, const SwVec2& p_max, SwU32 col, float rounding = 0.0f, SwDrawFlags flags = 0, float thickness = 1.0f);   // a: upper-left, b: lower-right (== upper-left + size)
    SW_API void                   RectFilled(const SwVec2& p_min, const SwVec2& p_max, SwU32 col, float rounding = 0.0f, SwDrawFlags flags = 0);                     // a: upper-left, b: lower-right (== upper-left + size)
    SW_API void                   RectFilledMultiColor(const SwVec2& p_min, const SwVec2& p_max, SwU32 col_upr_left, SwU32 col_upr_right, SwU32 col_bot_right, SwU32 col_bot_left);
    SW_API void                   Quad(const SwVec2& p1, const SwVec2& p2, const SwVec2& p3, const SwVec2& p4, SwU32 col, float thickness = 1.0f);
    SW_API void                   QuadFilled(const SwVec2& p1, const SwVec2& p2, const SwVec2& p3, const SwVec2& p4, SwU32 col);
    SW_API void                   Triangle(const SwVec2& p1, const SwVec2& p2, const SwVec2& p3, SwU32 col, float thickness = 1.0f);
    SW_API void                   TriangleFilled(const SwVec2& p1, const SwVec2& p2, const SwVec2& p3, SwU32 col);
    SW_API void                   Circle(const SwVec2& center, float radius, SwU32 col, int num_segments = 0, float thickness = 1.0f);
    SW_API void                   CircleFilled(const SwVec2& center, float radius, SwU32 col, int num_segments = 0);
    SW_API void                   Ngon(const SwVec2& center, float radius, SwU32 col, int num_segments, float thickness = 1.0f);
    SW_API void                   NgonFilled(const SwVec2& center, float radius, SwU32 col, int num_segments);
    SW_API void                   Polyline(SwVec2* points, int num_points, SwU32 col, SwDrawFlags flags, float thickness);
    SW_API void                   ConvexPolyFilled(SwVec2* points, int num_points, SwU32 col);
    SW_API void                   BezierCubic(const SwVec2& p1, const SwVec2& p2, const SwVec2& p3, const SwVec2& p4, SwU32 col, float thickness, int num_segments = 0); // Cubic Bezier (4 control points)
    SW_API void                   BezierQuadratic(const SwVec2& p1, const SwVec2& p2, const SwVec2& p3, SwU32 col, float thickness, int num_segments = 0);               // Quadratic Bezier (3 control points)

    // 3D graphics
    SW_API void                   Sphere(const char* name, const float size, const SwVec2& pos, SwVec4& axes, const int tessFactor = 2);
    SW_API void                   Cube(const char* name, const float size, const SwVec2& pos, SwVec4& axes);
    SW_API void                   Cone(const char* name, const float length, const float radius, const int slices, const float size, const SwVec2& pos, SwVec4& axes);

    // CV
    SW_API void                   OpenVideo(const char* file_name);

    // Widgets: Text
    SW_API void                   TextUnformatted(const char* text, const char* text_end = NULL); // raw text without formatting. Roughly equivalent to Text("%s", text) but: A) doesn't require null terminated string if 'text_end' is specified, B) it's faster, no memory copy is done, no buffer size limits, recommended for long chunks of text.
    SW_API void                   Text(const char* fmt, ...)                                          SW_FMTARGS(1); // formatted text
    SW_API void                   TextV(const char* fmt, va_list args)                                SW_FMTLIST(1);
    SW_API void                   TextColored(const SwVec4& col, const char* fmt, ...)              SW_FMTARGS(2); // shortcut for PushStyleColor(SwGuiCol_Text, col); Text(fmt, ...); PopStyleColor();
    SW_API void                   TextColoredV(const SwVec4& col, const char* fmt, va_list args)    SW_FMTLIST(2);
    SW_API void                   TextWrapped(const char* fmt, ...)                                   SW_FMTARGS(1); // shortcut for PushTextWrapPos(0.0f); Text(fmt, ...); PopTextWrapPos();. Note that this won't work on an auto-resizing window if there's no other widgets to extend the window width, yoy may need to set a size using SetNextWindowSize().
    SW_API void                   TextWrappedV(const char* fmt, va_list args)                         SW_FMTLIST(1);

    // Widgets: Main
    // - Most widgets return true when the value has been changed or when pressed/selected
    // - You may also use one of the many IsItemXXX functions (e.g. IsItemActive, IsItemHovered, etc.) to query widget state.
    SW_API bool                   Button(const char* label, const SwVec2& size = SwVec2(0, 0));   // button
    SW_API bool                   SmallButton(const char* label);                                 // button with (FramePadding.y == 0) to easily embed within text
    SW_API bool                   InvisibleButton(const char* str_id, const SwVec2& size_arg, SwGuiButtonFlags flags = 0); // flexible button behavior without the visuals, frequently useful to build custom behaviors using the public api (along with IsItemActive, IsItemHovered, etc.)
    SW_API bool                   ArrowButton(const char* str_id, SwGuiDir dir);                  // square button with an arrow shape
    SW_API bool                   Checkbox(const char* label, bool* v);
    SW_API bool                   CheckboxFlags(const char* label, int* flags, int flags_value);
    SW_API bool                   CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value);
    SW_API bool                   RadioButton(const char* label, bool active);                    // use with e.g. if (RadioButton("one", my_value==1)) { my_value = 1; }
    SW_API bool                   RadioButton(const char* label, int* v, int v_button);           // shortcut to handle the above pattern when value is an integer
    SW_API void                   ProgressBar(float fraction, const SwVec2& size_arg = SwVec2(-FLT_MIN, 0), const char* overlay = NULL);
    SW_API void                   Bullet();                                                       // draw a small circle + keep the cursor on the same line. advance cursor x position by GetTreeNodeToLabelSpacing(), same distance that TreeNode() uses

    // Widgets: Images
    SW_API void                   Image(SwTextureID user_texture_id, const SwVec2& size, const SwVec2& uv0 = SwVec2(0, 0), const SwVec2& uv1 = SwVec2(1, 1), const SwVec4& tint_col = SwVec4(1, 1, 1, 1), const SwVec4& border_col = SwVec4(0, 0, 0, 0));

    // Widgets: Combo Box
    // - The BeginCombo()/EndCombo() api allows you to manage your contents and selection state however you want it, by creating e.g. Selectable() items.
    // - The old Combo() api are helpers over BeginCombo()/EndCombo() which are kept available for convenience purpose. This is analogous to how ListBox are created.
    SW_API bool                   BeginCombo(const char* label, const char* preview_value, SwGuiComboFlags flags = 0);
    SW_API void                   EndCombo(); // only call EndCombo() if BeginCombo() returns true!
    SW_API bool                   Combo(const char* label, int* current_item, const char* const items[], int items_count, int popup_max_height_in_items = -1);
    SW_API bool                   Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int popup_max_height_in_items = -1);      // Separate items with \0 within a string, end item-list with \0\0. e.g. "One\0Two\0Three\0"
    SW_API bool                   Combo(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), void* user_data, int items_count, int popup_max_height_in_items = -1);

    // Widgets: Drag Sliders
    SW_API bool                   DragFloat(const char* label, float* v, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", SwGuiSliderFlags flags = 0);     // If v_min >= v_max we have no bound
    SW_API bool                   DragFloat2(const char* label, float v[2], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", SwGuiSliderFlags flags = 0);
    SW_API bool                   DragFloat3(const char* label, float v[3], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", SwGuiSliderFlags flags = 0);
    SW_API bool                   DragFloat4(const char* label, float v[4], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", SwGuiSliderFlags flags = 0);
    SW_API bool                   DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", const char* format_max = NULL, SwGuiSliderFlags flags = 0);
    SW_API bool                   DragInt(const char* label, int* v, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", SwGuiSliderFlags flags = 0);  // If v_min >= v_max we have no bound
    SW_API bool                   DragInt2(const char* label, int v[2], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", SwGuiSliderFlags flags = 0);
    SW_API bool                   DragInt3(const char* label, int v[3], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", SwGuiSliderFlags flags = 0);
    SW_API bool                   DragInt4(const char* label, int v[4], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", SwGuiSliderFlags flags = 0);
    SW_API bool                   DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", const char* format_max = NULL, SwGuiSliderFlags flags = 0);
    SW_API bool                   DragScalar(const char* label, SwGuiDataType data_type, void* p_data, float v_speed = 1.0f, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, SwGuiSliderFlags flags = 0);
    SW_API bool                   DragScalarN(const char* label, SwGuiDataType data_type, void* p_data, int components, float v_speed = 1.0f, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, SwGuiSliderFlags flags = 0);

    // Widgets: Regular Sliders
    // - CTRL+Click on any slider to turn them into an input box. Manually input values aren't clamped by default and can go off-bounds. Use SwGuiSliderFlags_AlwaysClamp to always clamp.
    // - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc.
    // - Format string may also be set to NULL or use the default format ("%f" or "%d").
    // - Legacy: Pre-1.78 there are SliderXXX() function signatures that take a final `float power=1.0f' argument instead of the `SwGuiSliderFlags flags=0' argument.
    //   If you get a warning converting a float to SwGuiSliderFlags, read https://github.com/ocornut/imgui/issues/3361
    SW_API bool                   SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format = "%.3f", SwGuiSliderFlags flags = 0);     // adjust format to decorate the value with a prefix or a suffix for in-slider labels or unit display.
    SW_API bool                   SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format = "%.3f", SwGuiSliderFlags flags = 0);
    SW_API bool                   SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format = "%.3f", SwGuiSliderFlags flags = 0);
    SW_API bool                   SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format = "%.3f", SwGuiSliderFlags flags = 0);
    SW_API bool                   SliderAngle(const char* label, float* v_rad, float v_degrees_min = -360.0f, float v_degrees_max = +360.0f, const char* format = "%.0f deg", SwGuiSliderFlags flags = 0);
    SW_API bool                   SliderInt(const char* label, int* v, int v_min, int v_max, const char* format = "%d", SwGuiSliderFlags flags = 0);
    SW_API bool                   SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format = "%d", SwGuiSliderFlags flags = 0);
    SW_API bool                   SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format = "%d", SwGuiSliderFlags flags = 0);
    SW_API bool                   SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format = "%d", SwGuiSliderFlags flags = 0);
    SW_API bool                   SliderScalar(const char* label, SwGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, SwGuiSliderFlags flags = 0);
    SW_API bool                   SliderScalarN(const char* label, SwGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format = NULL, SwGuiSliderFlags flags = 0);
    SW_API bool                   VSliderFloat(const char* label, const SwVec2& size, float* v, float v_min, float v_max, const char* format = "%.3f", SwGuiSliderFlags flags = 0);
    SW_API bool                   VSliderInt(const char* label, const SwVec2& size, int* v, int v_min, int v_max, const char* format = "%d", SwGuiSliderFlags flags = 0);
    SW_API bool                   VSliderScalar(const char* label, const SwVec2& size, SwGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, SwGuiSliderFlags flags = 0);

    // Widgets: Selectables
    // - A selectable highlights when hovered, and can display another color when selected.
    // - Neighbors selectable extend their highlight bounds in order to leave no gap between them. This is so a series of selected Selectable appear contiguous.
    SW_API bool                   Selectable(const char* label, bool selected = false, SwGuiSelectableFlags flags = 0, const SwVec2& size = SwVec2(0, 0)); // "bool selected" carry the selection state (read-only). Selectable() is clicked is returns true so you can modify your selection state. size.x==0.0: use remaining width, size.x>0.0: specify width. size.y==0.0: use label height, size.y>0.0: specify height
    SW_API bool                   Selectable(const char* label, bool* p_selected, SwGuiSelectableFlags flags = 0, const SwVec2& size = SwVec2(0, 0));      // "bool* p_selected" point to the selection state (read-write), as a convenient helper.

    // Widgets: Menus
    // - Use BeginMenuBar() on a window SwGuiWindowFlags_MenuBar to append to its menu bar.
    // - Use BeginMainMenuBar() to create a menu bar at the top of the screen and append to it.
    // - Use BeginMenu() to create a menu. You can call BeginMenu() multiple time with the same identifier to append more items to it.
    // - Not that MenuItem() keyboardshortcuts are displayed as a convenience but _not processed_ by  SwGui at the moment.
    SW_API bool                   BeginMenuBar();                                                     // append to menu-bar of current window (requires SwGuiWindowFlags_MenuBar flag set on parent window).
    SW_API void                   EndMenuBar();                                                       // only call EndMenuBar() if BeginMenuBar() returns true!
    SW_API bool                   BeginMainMenuBar();                                                 // create and append to a full screen menu-bar.
    SW_API void                   EndMainMenuBar();                                                   // only call EndMainMenuBar() if BeginMainMenuBar() returns true!
    SW_API bool                   BeginMenu(const char* label, bool enabled = true);                  // create a sub-menu entry. only call EndMenu() if this returns true!
    SW_API void                   EndMenu();                                                          // only call EndMenu() if BeginMenu() returns true!
    SW_API bool                   MenuItem(const char* label, const char* shortcut = NULL, bool selected = false, bool enabled = true);  // return true when activated.
    SW_API bool                   MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled = true);

    // Tooltips
    // - Tooltip are windows following the mouse. They do not take focus away.
    SW_API void                   BeginTooltip();                                                     // begin/append a tooltip window. to create full-featured tooltip (with any kind of items).
    SW_API void                   EndTooltip();
    SW_API void                   SetTooltip(const char* fmt, ...) SW_FMTARGS(1);                     // set a text-only tooltip, typically use with SW::IsItemHovered(). override any previous call to SetTooltip().
    SW_API void                   SetTooltipV(const char* fmt, va_list args) SW_FMTLIST(1);

    // Popups, Modals
    //  - They block normal mouse hovering detection (and therefore most mouse interactions) behind them.
    //  - If not modal: they can be closed by clicking anywhere outside them, or by pressing ESCAPE.
    //  - Their visibility state (~bool) is held internally instead of being held by the programmer as we are used to with regular Begin*() calls.
    //  - The 3 properties above are related: we need to retain popup visibility state in the library because popups may be closed as any time.
    //  - You can bypass the hovering restriction by using SwGuiHoveredFlags_AllowWhenBlockedByPopup when calling IsItemHovered() or IsWindowHovered().
    //  - IMPORTANT: Popup identifiers are relative to the current ID stack, so OpenPopup and BeginPopup generally needs to be at the same level of the stack.
    //    This is sometimes leading to confusing mistakes. May rework this in the future.

    // Popups: begin/end functions
    //  - BeginPopup(): query popup state, if open start appending into the window. Call EndPopup() afterwards. SwGuiWindowFlags are forwarded to the window.
    //  - BeginPopupModal(): block every interaction behind the window, cannot be closed by user, add a dimming background, has a title bar.
    SW_API bool                   BeginPopup(const char* str_id, SwGuiWindowFlags flags = 0);                         // return true if the popup is open, and you can start outputting to it.
    SW_API bool                   BeginPopupModal(const char* name, bool* p_open = NULL, SwGuiWindowFlags flags = 0); // return true if the modal is open, and you can start outputting to it.
    SW_API void                   EndPopup();                                                                         // only call EndPopup() if BeginPopupXXX() returns true!

    // Popups: open/close functions
    //  - OpenPopup(): set popup state to open. SwGuiPopupFlags are available for opening options.
    //  - If not modal: they can be closed by clicking anywhere outside them, or by pressing ESCAPE.
    //  - CloseCurrentPopup(): use inside the BeginPopup()/EndPopup() scope to close manually.
    //  - CloseCurrentPopup() is called by default by Selectable()/MenuItem() when activated (FIXME: need some options).
    //  - Use SwGuiPopupFlags_NoOpenOverExistingPopup to avoid opening a popup if there's already one at the same level. This is equivalent to e.g. testing for !IsAnyPopupOpen() prior to OpenPopup().
    //  - Use IsWindowAppearing() after BeginPopup() to tell if a window just opened.
    //  - IMPORTANT: Notice that for OpenPopupOnItemClick() we exceptionally default flags to 1 (== SwGuiPopupFlags_MouseButtonRight) for backward compatibility with older API taking 'int mouse_button = 1' parameter
    SW_API void                   OpenPopup(const char* str_id, SwGuiPopupFlags popup_flags = 0);                     // call to mark popup as open (don't call every frame!).
    SW_API void                   OpenPopup(SwGuiID id, SwGuiPopupFlags popup_flags = 0);                             // id overload to facilitate calling from nested stacks
    SW_API void                   OpenPopupOnItemClick(const char* str_id = NULL, SwGuiPopupFlags popup_flags = 1);   // helper to open popup when clicked on last item. Default to SwGuiPopupFlags_MouseButtonRight == 1. (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors)
    SW_API void                   CloseCurrentPopup();                                                                // manually close the popup we have begin-ed into.

    // Popups: open+begin combined functions helpers
    //  - Helpers to do OpenPopup+BeginPopup where the Open action is triggered by e.g. hovering an item and right-clicking.
    //  - They are convenient to easily create context menus, hence the name.
    //  - IMPORTANT: Notice that BeginPopupContextXXX takes SwGuiPopupFlags just like OpenPopup() and unlike BeginPopup(). For full consistency, we may add SwGuiWindowFlags to the BeginPopupContextXXX functions in the future.
    //  - IMPORTANT: Notice that we exceptionally default their flags to 1 (== SwGuiPopupFlags_MouseButtonRight) for backward compatibility with older API taking 'int mouse_button = 1' parameter, so if you add other flags remember to re-add the SwGuiPopupFlags_MouseButtonRight.
    SW_API bool                   BeginPopupContextItem(const char* str_id = NULL, SwGuiPopupFlags popup_flags = 1);  // open+begin popup when clicked on last item. Use str_id==NULL to associate the popup to previous item. If you want to use that on a non-interactive item such as Text() you need to pass in an explicit ID here. read comments in .cpp!
    SW_API bool                   BeginPopupContextWindow(const char* str_id = NULL, SwGuiPopupFlags popup_flags = 1);// open+begin popup when clicked on current window.
    SW_API bool                   BeginPopupContextVoid(const char* str_id = NULL, SwGuiPopupFlags popup_flags = 1);  // open+begin popup when clicked in void (where there are no windows).

    // Popups: query functions
    //  - IsPopupOpen(): return true if the popup is open at the current BeginPopup() level of the popup stack.
    //  - IsPopupOpen() with SwGuiPopupFlags_AnyPopupId: return true if any popup is open at the current BeginPopup() level of the popup stack.
    //  - IsPopupOpen() with SwGuiPopupFlags_AnyPopupId + SwGuiPopupFlags_AnyPopupLevel: return true if any popup is open.
    SW_API bool                   IsPopupOpen(const char* str_id, SwGuiPopupFlags flags = 0);                         // return true if the popup is open.


    // Docking
    // [BETA API] Enable with io.ConfigFlags |= SwGuiConfigFlags_DockingEnable.
    // Note: You can use most Docking facilities without calling any API. You DO NOT need to call DockSpace() to use Docking!
    // - Drag from window title bar or their tab to dock/undock. Hold SHIFT to disable docking/undocking.
    // - Drag from window menu button (upper-left button) to undock an entire node (all windows).
    // - When io.ConfigDockingWithShift == true, you instead need to hold SHIFT to _enable_ docking/undocking.
    // About dockspaces:
    // - Use DockSpace() to create an explicit dock node _within_ an existing window. See Docking demo for details.
    // - Use DockSpaceOverViewport() to create an explicit dock node covering the screen or a specific viewport.
    //   This is often used with SwGuiDockNodeFlags_PassthruCentralNode.
    // - Important: Dockspaces need to be submitted _before_ any window they can host. Submit it early in your frame!
    // - Important: Dockspaces need to be kept alive if hidden, otherwise windows docked into it will be undocked.
    //   e.g. if you have multiple tabs with a dockspace inside each tab: submit the non-visible dockspaces with SwGuiDockNodeFlags_KeepAliveOnly.
    SW_API SwGuiID                DockSpace(SwGuiID id, const SwVec2& size = SwVec2(0, 0), SwGuiDockNodeFlags flags = 0, const SwGuiWindowClass* window_class = NULL);
    SW_API SwGuiID                DockSpaceOverViewport(const SwGuiViewport* viewport = NULL, SwGuiDockNodeFlags flags = 0, const SwGuiWindowClass* window_class = NULL);
    SW_API void                   SetNextWindowDockID(SwGuiID dock_id, SwGuiCond cond = 0);           // set next window dock id
    SW_API void                   SetNextWindowClass(const SwGuiWindowClass* window_class);           // set next window class (control docking compatibility + provide hints to platform backend via custom viewport flags and platform parent/child relationship)
    SW_API SwGuiID                GetWindowDockID();
    SW_API bool                   IsWindowDocked();                                                   // is current window docked into another window?

    // Texture
    SW_API SwTexture              CreateTexture(const char* imagePath);
    SW_API SwTexture              CreateGrayTexture(const char* imagePath);

    // Item/Widgets Utilities and Query Functions
    // - Most of the functions are referring to the previous Item that has been submitted.
    // - See Demo Window under "Widgets->Querying Status" for an interactive visualization of most of those functions.
    SW_API bool                   IsItemHovered(SwGuiHoveredFlags flags = 0);                         // is the last item hovered? (and usable, aka not blocked by a popup, etc.). See SwGuiHoveredFlags for more options.
    SW_API bool                   IsItemActive();                                                     // is the last item active? (e.g. button being held, text field being edited. This will continuously return true while holding mouse button on an item. Items that don't interact will always return false)
    SW_API bool                   IsItemFocused();                                                    // is the last item focused for keyboard/gamepad navigation?
    SW_API bool                   IsItemClicked(SwGuiMouseButton mouse_button = 0);                   // is the last item hovered and mouse clicked on? (**)  == IsMouseClicked(mouse_button) && IsItemHovered()Important. (**) this is NOT equivalent to the behavior of e.g. Button(). Read comments in function definition.
    SW_API bool                   IsItemVisible();                                                    // is the last item visible? (items may be out of sight because of clipping/scrolling)
    SW_API bool                   IsItemEdited();                                                     // did the last item modify its underlying value this frame? or was pressed? This is generally the same as the "bool" return value of many widgets.
    SW_API bool                   IsItemActivated();                                                  // was the last item just made active (item was previously inactive).
    SW_API bool                   IsItemDeactivated();                                                // was the last item just made inactive (item was previously active). Useful for Undo/Redo patterns with widgets that require continuous editing.
    SW_API bool                   IsItemDeactivatedAfterEdit();                                       // was the last item just made inactive and made a value change when it was active? (e.g. Slider/Drag moved). Useful for Undo/Redo patterns with widgets that require continuous editing. Note that you may get false positives (some widgets such as Combo()/ListBox()/Selectable() will return true even when clicking an already selected item).
    SW_API bool                   IsItemToggledOpen();                                                // was the last item open state toggled? set by TreeNode().
    SW_API bool                   IsAnyItemHovered();                                                 // is any item hovered?
    SW_API bool                   IsAnyItemActive();                                                  // is any item active?
    SW_API bool                   IsAnyItemFocused();                                                 // is any item focused?
    SW_API SwVec2                 GetItemRectMin();                                                   // get upper-left bounding rectangle of the last item (screen space)
    SW_API SwVec2                 GetItemRectMax();                                                   // get lower-right bounding rectangle of the last item (screen space)
    SW_API SwVec2                 GetItemRectSize();                                                  // get size of last item
    SW_API void                   SetItemAllowOverlap();                                              // allow last item to be overlapped by a subsequent item. sometimes useful with invisible buttons, selectables, etc. to catch unused area.


    // Tab Bars, Tabs
    // Note: Tabs are automatically created by the docking system. Use this to create tab bars/tabs yourself without docking being involved.
    SW_API bool                   BeginTabBar(const char* str_id, SwGuiTabBarFlags flags = 0);        // create and append into a TabBar
    SW_API void                   EndTabBar();                                                        // only call EndTabBar() if BeginTabBar() returns true!
    SW_API bool                   BeginTabItem(const char* label, bool* p_open = NULL, SwGuiTabItemFlags flags = 0); // create a Tab. Returns true if the Tab is selected.
    SW_API void                   EndTabItem();                                                       // only call EndTabItem() if BeginTabItem() returns true!
    SW_API bool                   TabItemButton(const char* label, SwGuiTabItemFlags flags = 0);      // create a Tab behaving like a button. return true when clicked. cannot be selected in the tab bar.
    SW_API void                   SetTabItemClosed(const char* tab_or_docked_window_label);           // notify TabBar or Docking system of a closed tab/window ahead (useful to reduce visual flicker on reorderable tab bars). For tab-bar: call after BeginTabBar() and before Tab submissions. Otherwise call with a window name.


    // Logging/Capture
    // - All text output from the interface can be captured into tty/file/clipboard. By default, tree nodes are automatically opened during logging.
    SW_API void                   LogText(const char* fmt, ...) SW_FMTARGS(1);                        // pass text data straight to log (without being displayed)
    SW_API void                   LogTextV(const char* fmt, va_list args) SW_FMTLIST(1);


    // Drag and Drop
    // - On source items, call BeginDragDropSource(), if it returns true also call SetDragDropPayload() + EndDragDropSource().
    // - On target candidates, call BeginDragDropTarget(), if it returns true also call AcceptDragDropPayload() + EndDragDropTarget().
    // - If you stop calling BeginDragDropSource() the payload is preserved however it won't have a preview tooltip (we currently display a fallback "..." tooltip, see #1725)
    // - An item can be both drag source and drop target.
    SW_API bool                   BeginDragDropSource(SwGuiDragDropFlags flags = 0);                                      // call after submitting an item which may be dragged. when this return true, you can call SetDragDropPayload() + EndDragDropSource()
    SW_API bool                   SetDragDropPayload(const char* type, const void* data, size_t sz, SwGuiCond cond = 0);  // type is a user defined string of maximum 32 characters. Strings starting with '_' are reserved for  imgui internal types. Data is copied and held by imgui. Return true when payload has been accepted.
    SW_API void                   EndDragDropSource();                                                                    // only call EndDragDropSource() if BeginDragDropSource() returns true!
    SW_API bool                   BeginDragDropTarget();                                                          // call after submitting an item that may receive a payload. If this returns true, you can call AcceptDragDropPayload() + EndDragDropTarget()
    SW_API const SwGuiPayload*    AcceptDragDropPayload(const char* type, SwGuiDragDropFlags flags = 0);          // accept contents of a given type. If SwGuiDragDropFlags_AcceptBeforeDelivery is set you can peek into the payload before the mouse button is released.
    SW_API void                   EndDragDropTarget();                                                            // only call EndDragDropTarget() if BeginDragDropTarget() returns true!
    SW_API const SwGuiPayload*    GetDragDropPayload();                                                           // peek directly into the current payload from anywhere. may return NULL. use SwGuiPayload::IsDataType() to test for the payload type.

    // Text Utilities
    SW_API SwVec2                 CalcTextSize(const char* text, const char* text_end = NULL, bool hide_text_after_double_hash = false, float wrap_width = -1.0f);

    // Settings/.Ini Utilities
    // - The disk functions are automatically called if io.IniFilename != NULL (default is "imgui.ini").
    // - Set io.IniFilename to NULL to load/save manually. Read io.WantSaveIniSettings description about handling .ini saving manually.
    // - Important: default value "imgui.ini" is relative to current working dir! Most apps will want to lock this to an absolute path (e.g. same path as executables).
    SW_API void                   LoadIniSettingsFromDisk(const char* ini_filename);                      // call after CreateContext() and before the first call to NewFrame(). NewFrame() automatically calls LoadIniSettingsFromDisk(io.IniFilename).
    SW_API void                   LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size = 0);   // call after CreateContext() and before the first call to NewFrame() to provide .ini data from your own data source.
    SW_API void                   SaveIniSettingsToDisk(const char* ini_filename);                        // this is automatically called (if io.IniFilename is not empty) a few seconds after any modification that should be reflected in the .ini file (and also by DestroyContext).
    SW_API const char*            SaveIniSettingsToMemory(size_t* out_ini_size = NULL);                   // return a zero-terminated string with the .ini data which you can save by your own mean. call when io.WantSaveIniSettings is set, then save data by your own mean and clear io.WantSaveIniSettings.
}

//-----------------------------------------------------------------------------
// [SECTION] Flags & Enumerations
//-----------------------------------------------------------------------------

// Flags for SW::Begin()
enum SwGuiWindowFlags_
{
    SwGuiWindowFlags_None = 0,
    SwGuiWindowFlags_NoTitleBar = 1 << 0,   // Disable title-bar
    SwGuiWindowFlags_NoResize = 1 << 1,   // Disable user resizing with the lower-right grip
    SwGuiWindowFlags_NoMove = 1 << 2,   // Disable user moving the window
    SwGuiWindowFlags_NoScrollbar = 1 << 3,   // Disable scrollbars (window can still scroll with mouse or programmatically)
    SwGuiWindowFlags_NoScrollWithMouse = 1 << 4,   // Disable user vertically scrolling with mouse wheel. On child window, mouse wheel will be forwarded to the parent unless NoScrollbar is also set.
    SwGuiWindowFlags_NoCollapse = 1 << 5,   // Disable user collapsing window by double-clicking on it. Also referred to as Window Menu Button (e.g. within a docking node).
    SwGuiWindowFlags_AlwaysAutoResize = 1 << 6,   // Resize every window to its content every frame
    SwGuiWindowFlags_NoBackground = 1 << 7,   // Disable drawing background color (WindowBg, etc.) and outside border. Similar as using SetNextWindowBgAlpha(0.0f).
    SwGuiWindowFlags_NoSavedSettings = 1 << 8,   // Never load/save settings in .ini file
    SwGuiWindowFlags_NoMouseInputs = 1 << 9,   // Disable catching mouse, hovering test with pass through.
    SwGuiWindowFlags_MenuBar = 1 << 10,  // Has a menu-bar
    SwGuiWindowFlags_HorizontalScrollbar = 1 << 11,  // Allow horizontal scrollbar to appear (off by default). You may use SetNextWindowContentSize(SwVec2(width,0.0f)); prior to calling Begin() to specify width. Read code in mgui_demo in the "Horizontal Scrolling" section.
    SwGuiWindowFlags_NoFocusOnAppearing = 1 << 12,  // Disable taking focus when transitioning from hidden to visible state
    SwGuiWindowFlags_NoBringToFrontOnFocus = 1 << 13,  // Disable bringing window to front when taking focus (e.g. clicking on it or programmatically giving it focus)
    SwGuiWindowFlags_AlwaysVerticalScrollbar = 1 << 14,  // Always show vertical scrollbar (even if ContentSize.y < Size.y)
    SwGuiWindowFlags_AlwaysHorizontalScrollbar = 1 << 15,  // Always show horizontal scrollbar (even if ContentSize.x < Size.x)
    SwGuiWindowFlags_AlwaysUseWindowPadding = 1 << 16,  // Ensure child windows without border uses style.WindowPadding (ignored by default for non-bordered child windows, because more convenient)
    SwGuiWindowFlags_NoNavInputs = 1 << 18,  // No gamepad/keyboard navigation within the window
    SwGuiWindowFlags_NoNavFocus = 1 << 19,  // No focusing toward this window with gamepad/keyboard navigation (e.g. skipped by CTRL+TAB)
    SwGuiWindowFlags_UnsavedDocument = 1 << 20,  // Display a dot next to the title. When used in a tab/docking context, tab is selected when clicking the X + closure is not assumed (will wait for user to stop submitting the tab). Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar.
    SwGuiWindowFlags_NoDocking = 1 << 21,  // Disable docking of this window

    SwGuiWindowFlags_NoNav = SwGuiWindowFlags_NoNavInputs | SwGuiWindowFlags_NoNavFocus,
    SwGuiWindowFlags_NoDecoration = SwGuiWindowFlags_NoTitleBar | SwGuiWindowFlags_NoResize | SwGuiWindowFlags_NoScrollbar | SwGuiWindowFlags_NoCollapse,
    SwGuiWindowFlags_NoInputs = SwGuiWindowFlags_NoMouseInputs | SwGuiWindowFlags_NoNavInputs | SwGuiWindowFlags_NoNavFocus,

    // [Internal]
    SwGuiWindowFlags_NavFlattened = 1 << 23,  // [BETA] On child window: allow gamepad/keyboard navigation to cross over parent border to this child or between sibling child windows.
    SwGuiWindowFlags_ChildWindow = 1 << 24,  // Don't use! For internal use by BeginChild()
    SwGuiWindowFlags_Tooltip = 1 << 25,  // Don't use! For internal use by BeginTooltip()
    SwGuiWindowFlags_Popup = 1 << 26,  // Don't use! For internal use by BeginPopup()
    SwGuiWindowFlags_Modal = 1 << 27,  // Don't use! For internal use by BeginPopupModal()
    SwGuiWindowFlags_ChildMenu = 1 << 28,  // Don't use! For internal use by BeginMenu()
    SwGuiWindowFlags_DockNodeHost = 1 << 29,  // Don't use! For internal use by Begin()/NewFrame()
};


// Flags for SW::BeginChild()
// (Legacy: bit 0 must always correspond to SwGuiChildFlags_Border to be backward compatible with old API using 'bool border'.
// About using AutoResizeX/AutoResizeY flags:
// - May be combined with SetNextWindowSizeConstraints() to set a min/max size for each axis (see "Demo->Child->Auto-resize with Constraints").
// - Size measurement for a given axis is only performed when the child window is within visible boundaries, or is just appearing.
//   - This allows BeginChild() to return false when not within boundaries (e.g. when scrolling), which is more optimal. BUT it won't update its auto-size while clipped.
//     While not perfect, it is a better default behavior as the always-on performance gain is more valuable than the occasional "resizing after becoming visible again" glitch.
//   - You may also use SwGuiChildFlags_AlwaysAutoResize to force an update even when child window is not in view.
//     HOWEVER PLEASE UNDERSTAND THAT DOING SO WILL PREVENT BeginChild() FROM EVER RETURNING FALSE, disabling benefits of coarse clipping.
enum SwGuiChildFlags_
{
    SwGuiChildFlags_None = 0,
    SwGuiChildFlags_Border = 1 << 0,   // Show an outer border and enable WindowPadding. (Important: this is always == 1 for legacy reason)
    SwGuiChildFlags_AlwaysUseWindowPadding = 1 << 1,   // Pad with style.WindowPadding even if no border are drawn (no padding by default for non-bordered child windows because it makes more sense)
    SwGuiChildFlags_ResizeX = 1 << 2,   // Allow resize from right border (layout direction). Enable .ini saving (unless SwGuiWindowFlags_NoSavedSettings passed to window flags)
    SwGuiChildFlags_ResizeY = 1 << 3,   // Allow resize from bottom border (layout direction). "
    SwGuiChildFlags_AutoResizeX = 1 << 4,   // Enable auto-resizing width. Read "IMPORTANT: Size measurement" details above.
    SwGuiChildFlags_AutoResizeY = 1 << 5,   // Enable auto-resizing height. Read "IMPORTANT: Size measurement" details above.
    SwGuiChildFlags_AlwaysAutoResize = 1 << 6,   // Combined with AutoResizeX/AutoResizeY. Always measure size even when child is hidden, always return true, always disable clipping optimization! NOT RECOMMENDED.
    SwGuiChildFlags_FrameStyle = 1 << 7,   // Style the child window like a framed item: use FrameBg, FrameRounding, FrameBorderSize, FramePadding instead of ChildBg, ChildRounding, ChildBorderSize, WindowPadding.
};

// Flags for SW::InputText()
enum SwGuiInputTextFlags_
{
    SwGuiInputTextFlags_None = 0,
    SwGuiInputTextFlags_CharsDecimal = 1 << 0,   // Allow 0123456789.+-*/
    SwGuiInputTextFlags_CharsHexadecimal = 1 << 1,   // Allow 0123456789ABCDEFabcdef
    SwGuiInputTextFlags_CharsUppercase = 1 << 2,   // Turn a..z into A..Z
    SwGuiInputTextFlags_CharsNoBlank = 1 << 3,   // Filter out spaces, tabs
    SwGuiInputTextFlags_AutoSelectAll = 1 << 4,   // Select entire text when first taking mouse focus
    SwGuiInputTextFlags_EnterReturnsTrue = 1 << 5,   // Return 'true' when Enter is pressed (as opposed to every time the value was modified). Consider looking at the IsItemDeactivatedAfterEdit() function.
    SwGuiInputTextFlags_CallbackCompletion = 1 << 6,   // Callback on pressing TAB (for completion handling)
    SwGuiInputTextFlags_CallbackHistory = 1 << 7,   // Callback on pressing Up/Down arrows (for history handling)
    SwGuiInputTextFlags_CallbackAlways = 1 << 8,   // Callback on each iteration. User code may query cursor position, modify text buffer.
    SwGuiInputTextFlags_CallbackCharFilter = 1 << 9,   // Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard.
    SwGuiInputTextFlags_AllowTabInput = 1 << 10,  // Pressing TAB input a '\t' character into the text field
    SwGuiInputTextFlags_CtrlEnterForNewLine = 1 << 11,  // In multi-line mode, unfocus with Enter, add new line with Ctrl+Enter (default is opposite: unfocus with Ctrl+Enter, add line with Enter).
    SwGuiInputTextFlags_NoHorizontalScroll = 1 << 12,  // Disable following the cursor horizontally
    SwGuiInputTextFlags_AlwaysOverwrite = 1 << 13,  // Overwrite mode
    SwGuiInputTextFlags_ReadOnly = 1 << 14,  // Read-only mode
    SwGuiInputTextFlags_Password = 1 << 15,  // Password mode, display all characters as '*'
    SwGuiInputTextFlags_NoUndoRedo = 1 << 16,  // Disable undo/redo. Note that input text owns the text data while active, if you want to provide your own undo/redo stack you need e.g. to call ClearActiveID().
    SwGuiInputTextFlags_CharsScientific = 1 << 17,  // Allow 0123456789.+-*/eE (Scientific notation input)
    SwGuiInputTextFlags_CallbackResize = 1 << 18,  // Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow. Notify when the string wants to be resized (for string types which hold a cache of their Size). You will be provided a new BufSize in the callback and NEED to honor it. (see misc/cpp/mgui_stdlib.h for an example of using this)
    SwGuiInputTextFlags_CallbackEdit = 1 << 19,  // Callback on any edit (note that InputText() already returns true on edit, the callback is useful mainly to manipulate the underlying buffer while focus is active)
    SwGuiInputTextFlags_EscapeClearsAll = 1 << 20,  // Escape key clears content if not empty, and deactivate otherwise (constrast to default behavior of Escape to revert)

    // Obsolete names (will be removed soon)
#ifndef SW_DISABLE_OBSOLETE_FUNCTIONS
    SwGuiInputTextFlags_AlwaysInsertMode = SwGuiInputTextFlags_AlwaysOverwrite   // [renamed in 1.82] name was not matching behavior
#endif
};

// Flags for SW::TreeNodeEx(), SW::CollapsingHeader*()
enum SwGuiTreeNodeFlags_
{
    SwGuiTreeNodeFlags_None = 0,
    SwGuiTreeNodeFlags_Selected = 1 << 0,   // Draw as selected
    SwGuiTreeNodeFlags_Framed = 1 << 1,   // Draw frame with background (e.g. for CollapsingHeader)
    SwGuiTreeNodeFlags_AllowItemOverlap = 1 << 2,   // Hit testing to allow subsequent widgets to overlap this one
    SwGuiTreeNodeFlags_NoTreePushOnOpen = 1 << 3,   // Don't do a TreePush() when open (e.g. for CollapsingHeader) = no extra indent nor pushing on ID stack
    SwGuiTreeNodeFlags_NoAutoOpenOnLog = 1 << 4,   // Don't automatically and temporarily open node when Logging is active (by default logging will automatically open tree nodes)
    SwGuiTreeNodeFlags_DefaultOpen = 1 << 5,   // Default node to be open
    SwGuiTreeNodeFlags_OpenOnDoubleClick = 1 << 6,   // Need double-click to open node
    SwGuiTreeNodeFlags_OpenOnArrow = 1 << 7,   // Only open when clicking on the arrow part. If SwGuiTreeNodeFlags_OpenOnDoubleClick is also set, single-click arrow or double-click all box to open.
    SwGuiTreeNodeFlags_Leaf = 1 << 8,   // No collapsing, no arrow (use as a convenience for leaf nodes).
    SwGuiTreeNodeFlags_Bullet = 1 << 9,   // Display a bullet instead of arrow
    SwGuiTreeNodeFlags_FramePadding = 1 << 10,  // Use FramePadding (even for an unframed text node) to vertically align text baseline to regular widget height. Equivalent to calling AlignTextToFramePadding().
    SwGuiTreeNodeFlags_SpanAvailWidth = 1 << 11,  // Extend hit box to the right-most edge, even if not framed. This is not the default in order to allow adding other items on the same line. In the future we may refactor the hit system to be front-to-back, allowing natural overlaps and then this can become the default.
    SwGuiTreeNodeFlags_SpanFullWidth = 1 << 12,  // Extend hit box to the left-most and right-most edges (bypass the indented area).
    SwGuiTreeNodeFlags_NavLeftJumpsBackHere = 1 << 13,  // (WIP) Nav: left direction may move to this TreeNode() from any of its child (items submitted between TreeNode and TreePop)
    //SwGuiTreeNodeFlags_NoScrollOnOpen     = 1 << 14,  // FIXME: TODO: Disable automatic scroll on TreePop() if node got just open and contents is not visible
    SwGuiTreeNodeFlags_CollapsingHeader = SwGuiTreeNodeFlags_Framed | SwGuiTreeNodeFlags_NoTreePushOnOpen | SwGuiTreeNodeFlags_NoAutoOpenOnLog,
};

// Flags for OpenPopup*(), BeginPopupContext*(), IsPopupOpen() functions.
// - To be backward compatible with older API which took an 'int mouse_button = 1' argument, we need to treat
//   small flags values as a mouse button index, so we encode the mouse button in the first few bits of the flags.
//   It is therefore guaranteed to be legal to pass a mouse button index in SwGuiPopupFlags.
// - For the same reason, we exceptionally default the SwGuiPopupFlags argument of BeginPopupContextXXX functions to 1 instead of 0.
//   IMPORTANT: because the default parameter is 1 (==SwGuiPopupFlags_MouseButtonRight), if you rely on the default parameter
//   and want to use another flag, you need to pass in the SwGuiPopupFlags_MouseButtonRight flag explicitly.
// - Multiple buttons currently cannot be combined/or-ed in those functions (we could allow it later).
enum SwGuiPopupFlags_
{
    SwGuiPopupFlags_None = 0,
    SwGuiPopupFlags_MouseButtonLeft = 0,        // For BeginPopupContext*(): open on Left Mouse release. Guaranteed to always be == 0 (same as SwGuiMouseButton_Left)
    SwGuiPopupFlags_MouseButtonRight = 1,        // For BeginPopupContext*(): open on Right Mouse release. Guaranteed to always be == 1 (same as SwGuiMouseButton_Right)
    SwGuiPopupFlags_MouseButtonMiddle = 2,        // For BeginPopupContext*(): open on Middle Mouse release. Guaranteed to always be == 2 (same as SwGuiMouseButton_Middle)
    SwGuiPopupFlags_MouseButtonMask_ = 0x1F,
    SwGuiPopupFlags_MouseButtonDefault_ = 1,
    SwGuiPopupFlags_NoOpenOverExistingPopup = 1 << 5,   // For OpenPopup*(), BeginPopupContext*(): don't open if there's already a popup at the same level of the popup stack
    SwGuiPopupFlags_NoOpenOverItems = 1 << 6,   // For BeginPopupContextWindow(): don't return true when hovering items, only when hovering empty space
    SwGuiPopupFlags_AnyPopupId = 1 << 7,   // For IsPopupOpen(): ignore the SwGuiID parameter and test for any popup.
    SwGuiPopupFlags_AnyPopupLevel = 1 << 8,   // For IsPopupOpen(): search/test at any level of the popup stack (default test in the current level)
    SwGuiPopupFlags_AnyPopup = SwGuiPopupFlags_AnyPopupId | SwGuiPopupFlags_AnyPopupLevel,
};

// Flags for SW::Selectable()
enum SwGuiSelectableFlags_
{
    SwGuiSelectableFlags_None = 0,
    SwGuiSelectableFlags_DontClosePopups = 1 << 0,   // Clicking this doesn't close parent popup window
    SwGuiSelectableFlags_SpanAllColumns = 1 << 1,   // Selectable frame can span all columns (text will still fit in current column)
    SwGuiSelectableFlags_AllowDoubleClick = 1 << 2,   // Generate press events on double clicks too
    SwGuiSelectableFlags_Disabled = 1 << 3,   // Cannot be selected, display grayed out text
    SwGuiSelectableFlags_AllowItemOverlap = 1 << 4,   // (WIP) Hit testing to allow subsequent widgets to overlap this one
};

// Flags for SW::BeginCombo()
enum SwGuiComboFlags_
{
    SwGuiComboFlags_None = 0,
    SwGuiComboFlags_PopupAlignLeft = 1 << 0,   // Align the popup toward the left by default
    SwGuiComboFlags_HeightSmall = 1 << 1,   // Max ~4 items visible. Tip: If you want your combo popup to be a specific size you can use SetNextWindowSizeConstraints() prior to calling BeginCombo()
    SwGuiComboFlags_HeightRegular = 1 << 2,   // Max ~8 items visible (default)
    SwGuiComboFlags_HeightLarge = 1 << 3,   // Max ~20 items visible
    SwGuiComboFlags_HeightLargest = 1 << 4,   // As many fitting items as possible
    SwGuiComboFlags_NoArrowButton = 1 << 5,   // Display on the preview box without the square arrow button
    SwGuiComboFlags_NoPreview = 1 << 6,   // Display only a square arrow button
    SwGuiComboFlags_HeightMask_ = SwGuiComboFlags_HeightSmall | SwGuiComboFlags_HeightRegular | SwGuiComboFlags_HeightLarge | SwGuiComboFlags_HeightLargest,
};

// Flags for SW::BeginTabBar()
enum SwGuiTabBarFlags_
{
    SwGuiTabBarFlags_None = 0,
    SwGuiTabBarFlags_Reorderable = 1 << 0,   // Allow manually dragging tabs to re-order them + New tabs are appended at the end of list
    SwGuiTabBarFlags_AutoSelectNewTabs = 1 << 1,   // Automatically select new tabs when they appear
    SwGuiTabBarFlags_TabListPopupButton = 1 << 2,   // Disable buttons to open the tab list popup
    SwGuiTabBarFlags_NoCloseWithMiddleMouseButton = 1 << 3,   // Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You can still repro this behavior on user's side with if (IsItemHovered() && IsMouseClicked(2)) *p_open = false.
    SwGuiTabBarFlags_NoTabListScrollingButtons = 1 << 4,   // Disable scrolling buttons (apply when fitting policy is SwGuiTabBarFlags_FittingPolicyScroll)
    SwGuiTabBarFlags_NoTooltip = 1 << 5,   // Disable tooltips when hovering a tab
    SwGuiTabBarFlags_FittingPolicyResizeDown = 1 << 6,   // Resize tabs when they don't fit
    SwGuiTabBarFlags_FittingPolicyScroll = 1 << 7,   // Add scroll buttons when tabs don't fit
    SwGuiTabBarFlags_FittingPolicyMask_ = SwGuiTabBarFlags_FittingPolicyResizeDown | SwGuiTabBarFlags_FittingPolicyScroll,
    SwGuiTabBarFlags_FittingPolicyDefault_ = SwGuiTabBarFlags_FittingPolicyResizeDown,
};

// Flags for SW::BeginTabItem()
enum SwGuiTabItemFlags_
{
    SwGuiTabItemFlags_None = 0,
    SwGuiTabItemFlags_UnsavedDocument = 1 << 0,   // Display a dot next to the title + tab is selected when clicking the X + closure is not assumed (will wait for user to stop submitting the tab). Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar.
    SwGuiTabItemFlags_SetSelected = 1 << 1,   // Trigger flag to programmatically make the tab selected when calling BeginTabItem()
    SwGuiTabItemFlags_NoCloseWithMiddleMouseButton = 1 << 2,   // Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You can still repro this behavior on user's side with if (IsItemHovered() && IsMouseClicked(2)) *p_open = false.
    SwGuiTabItemFlags_NoPushId = 1 << 3,   // Don't call PushID(tab->ID)/PopID() on BeginTabItem()/EndTabItem()
    SwGuiTabItemFlags_NoTooltip = 1 << 4,   // Disable tooltip for the given tab
    SwGuiTabItemFlags_NoReorder = 1 << 5,   // Disable reordering this tab or having another tab cross over this tab
    SwGuiTabItemFlags_Leading = 1 << 6,   // Enforce the tab position to the left of the tab bar (after the tab list popup button)
    SwGuiTabItemFlags_Trailing = 1 << 7,   // Enforce the tab position to the right of the tab bar (before the scrolling buttons)
};

// Flags for SW::BeginTable()
// - Swportant! Sizing policies have complex and subtle side effects, much more so than you would expect.
//   Read comments/demos carefully + experiment with live demos to get acquainted with them.
// - The DEFAULT sizing policies are:
//    - Default to SwGuiTableFlags_SizingFixedFit    if ScrollX is on, or if host window has SwGuiWindowFlags_AlwaysAutoResize.
//    - Default to SwGuiTableFlags_SizingStretchSame if ScrollX is off.
// - When ScrollX is off:
//    - Table defaults to SwGuiTableFlags_SizingStretchSame -> all Columns defaults to SwGuiTableColumnFlags_WidthStretch with same weight.
//    - Columns sizing policy allowed: Stretch (default), Fixed/Auto.
//    - Fixed Columns (if any) will generally obtain their requested width (unless the table cannot fit them all).
//    - Stretch Columns will share the remaining width according to their respective weight.
//    - Mixed Fixed/Stretch columns is possible but has various side-effects on resizing behaviors.
//      The typical use of mixing sizing policies is: any number of LEADING Fixed columns, followed by one or two TRAILING Stretch columns.
//      (this is because the visible order of columns have subtle but necessary effects on how they react to manual resizing).
// - When ScrollX is on:
//    - Table defaults to SwGuiTableFlags_SizingFixedFit -> all Columns defaults to SwGuiTableColumnFlags_WidthFixed
//    - Columns sizing policy allowed: Fixed/Auto mostly.
//    - Fixed Columns can be enlarged as needed. Table will show a horizontal scrollbar if needed.
//    - When using auto-resizing (non-resizable) fixed columns, querying the content width to use item right-alignment e.g. SetNextItemWidth(-FLT_MIN) doesn't make sense, would create a feedback loop.
//    - Using Stretch columns OFTEN DOES NOT MAKE SENSE if ScrollX is on, UNLESS you have specified a value for 'inner_width' in BeginTable().
//      If you specify a value for 'inner_width' then effectively the scrolling space is known and Stretch or mixed Fixed/Stretch columns become meaningful again.
// - Read on documentation at the top of mgui_tables.cpp for details.
enum SwGuiTableFlags_
{
    // Features
    SwGuiTableFlags_None = 0,
    SwGuiTableFlags_Resizable = 1 << 0,   // Enable resizing columns.
    SwGuiTableFlags_Reorderable = 1 << 1,   // Enable reordering columns in header row (need calling TableSetupColumn() + TableHeadersRow() to display headers)
    SwGuiTableFlags_Hideable = 1 << 2,   // Enable hiding/disabling columns in context menu.
    SwGuiTableFlags_Sortable = 1 << 3,   // Enable sorting. Call TableGetSortSpecs() to obtain sort specs. Also see SwGuiTableFlags_SortMulti and SwGuiTableFlags_SortTristate.
    SwGuiTableFlags_NoSavedSettings = 1 << 4,   // Disable persisting columns order, width and sort settings in the .ini file.
    SwGuiTableFlags_ContextMenuInBody = 1 << 5,   // Right-click on columns body/contents will display table context menu. By default it is available in TableHeadersRow().
    // Decorations
    SwGuiTableFlags_RowBg = 1 << 6,   // Set each RowBg color with SwGuiCol_TableRowBg or SwGuiCol_TableRowBgAlt (equivalent of calling TableSetBgColor with SwGuiTableBgFlags_RowBg0 on each row manually)
    SwGuiTableFlags_BordersInnerH = 1 << 7,   // Draw horizontal borders between rows.
    SwGuiTableFlags_BordersOuterH = 1 << 8,   // Draw horizontal borders at the top and bottom.
    SwGuiTableFlags_BordersInnerV = 1 << 9,   // Draw vertical borders between columns.
    SwGuiTableFlags_BordersOuterV = 1 << 10,  // Draw vertical borders on the left and right sides.
    SwGuiTableFlags_BordersH = SwGuiTableFlags_BordersInnerH | SwGuiTableFlags_BordersOuterH, // Draw horizontal borders.
    SwGuiTableFlags_BordersV = SwGuiTableFlags_BordersInnerV | SwGuiTableFlags_BordersOuterV, // Draw vertical borders.
    SwGuiTableFlags_BordersInner = SwGuiTableFlags_BordersInnerV | SwGuiTableFlags_BordersInnerH, // Draw inner borders.
    SwGuiTableFlags_BordersOuter = SwGuiTableFlags_BordersOuterV | SwGuiTableFlags_BordersOuterH, // Draw outer borders.
    SwGuiTableFlags_Borders = SwGuiTableFlags_BordersInner | SwGuiTableFlags_BordersOuter,   // Draw all borders.
    SwGuiTableFlags_NoBordersInBody = 1 << 11,  // [ALPHA] Disable vertical borders in columns Body (borders will always appear in Headers). -> May move to style
    SwGuiTableFlags_NoBordersInBodyUntilResize = 1 << 12,  // [ALPHA] Disable vertical borders in columns Body until hovered for resize (borders will always appear in Headers). -> May move to style
    // Sizing Policy (read above for defaults)
    SwGuiTableFlags_SizingFixedFit = 1 << 13,  // Columns default to _WidthFixed or _WidthAuto (if resizable or not resizable), matching contents width.
    SwGuiTableFlags_SizingFixedSame = 2 << 13,  // Columns default to _WidthFixed or _WidthAuto (if resizable or not resizable), matching the maximum contents width of all columns. Swplicitly enable SwGuiTableFlags_NoKeepColumnsVisible.
    SwGuiTableFlags_SizingStretchProp = 3 << 13,  // Columns default to _WidthStretch with default weights proportional to each columns contents widths.
    SwGuiTableFlags_SizingStretchSame = 4 << 13,  // Columns default to _WidthStretch with default weights all equal, unless overridden by TableSetupColumn().
    // Sizing Extra Options
    SwGuiTableFlags_NoHostExtendX = 1 << 16,  // Make outer width auto-fit to columns, overriding outer_size.x value. Only available when ScrollX/ScrollY are disabled and Stretch columns are not used.
    SwGuiTableFlags_NoHostExtendY = 1 << 17,  // Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit). Only available when ScrollX/ScrollY are disabled. Data below the limit will be clipped and not visible.
    SwGuiTableFlags_NoKeepColumnsVisible = 1 << 18,  // Disable keeping column always minimally visible when ScrollX is off and table gets too small. Not recommended if columns are resizable.
    SwGuiTableFlags_PreciseWidths = 1 << 19,  // Disable distributing remainder width to stretched columns (width allocation on a 100-wide table with 3 columns: Without this flag: 33,33,34. With this flag: 33,33,33). With larger number of columns, resizing will appear to be less smooth.
    // Clipping
    SwGuiTableFlags_NoClip = 1 << 20,  // Disable clipping rectangle for every individual columns (reduce draw command count, items will be able to overflow into other columns). Generally incompatible with TableSetupScrollFreeze().
    // Padding
    SwGuiTableFlags_PadOuterX = 1 << 21,  // Default if BordersOuterV is on. Enable outermost padding. Generally desirable if you have headers.
    SwGuiTableFlags_NoPadOuterX = 1 << 22,  // Default if BordersOuterV is off. Disable outermost padding.
    SwGuiTableFlags_NoPadInnerX = 1 << 23,  // Disable inner padding between columns (double inner padding if BordersOuterV is on, single inner padding if BordersOuterV is off).
    // Scrolling
    SwGuiTableFlags_ScrollX = 1 << 24,  // Enable horizontal scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. Changes default sizing policy. Because this creates a child window, ScrollY is currently generally recommended when using ScrollX.
    SwGuiTableFlags_ScrollY = 1 << 25,  // Enable vertical scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size.
    // Sorting
    SwGuiTableFlags_SortMulti = 1 << 26,  // Hold shift when clicking headers to sort on multiple column. TableGetSortSpecs() may return specs where (SpecsCount > 1).
    SwGuiTableFlags_SortTristate = 1 << 27,  // Allow no sorting, disable default sorting. TableGetSortSpecs() may return specs where (SpecsCount == 0).

    // [Internal] Combinations and masks
    SwGuiTableFlags_SizingMask_ = SwGuiTableFlags_SizingFixedFit | SwGuiTableFlags_SizingFixedSame | SwGuiTableFlags_SizingStretchProp | SwGuiTableFlags_SizingStretchSame,

    // Obsolete names (will be removed soon)
#ifndef SW_DISABLE_OBSOLETE_FUNCTIONS
    //, SwGuiTableFlags_ColumnsWidthFixed = SwGuiTableFlags_SizingFixedFit, SwGuiTableFlags_ColumnsWidthStretch = SwGuiTableFlags_SizingStretchSame   // WIP Tables 2020/12
    //, SwGuiTableFlags_SizingPolicyFixed = SwGuiTableFlags_SizingFixedFit, SwGuiTableFlags_SizingPolicyStretch = SwGuiTableFlags_SizingStretchSame   // WIP Tables 2021/01
#endif
};

// Flags for SW::TableSetupColumn()
enum SwGuiTableColumnFlags_
{
    // Input configuration flags
    SwGuiTableColumnFlags_None = 0,
    SwGuiTableColumnFlags_Disabled = 1 << 0,   // Overriding/master disable flag: hide column, won't show in context menu (unlike calling TableSetColumnEnabled() which manipulates the user accessible state)
    SwGuiTableColumnFlags_DefaultHide = 1 << 1,   // Default as a hidden/disabled column.
    SwGuiTableColumnFlags_DefaultSort = 1 << 2,   // Default as a sorting column.
    SwGuiTableColumnFlags_WidthStretch = 1 << 3,   // Column will stretch. Preferable with horizontal scrolling disabled (default if table sizing policy is _SizingStretchSame or _SizingStretchProp).
    SwGuiTableColumnFlags_WidthFixed = 1 << 4,   // Column will not stretch. Preferable with horizontal scrolling enabled (default if table sizing policy is _SizingFixedFit and table is resizable).
    SwGuiTableColumnFlags_NoResize = 1 << 5,   // Disable manual resizing.
    SwGuiTableColumnFlags_NoReorder = 1 << 6,   // Disable manual reordering this column, this will also prevent other columns from crossing over this column.
    SwGuiTableColumnFlags_NoHide = 1 << 7,   // Disable ability to hide/disable this column.
    SwGuiTableColumnFlags_NoClip = 1 << 8,   // Disable clipping for this column (all NoClip columns will render in a same draw command).
    SwGuiTableColumnFlags_NoSort = 1 << 9,   // Disable ability to sort on this field (even if SwGuiTableFlags_Sortable is set on the table).
    SwGuiTableColumnFlags_NoSortAscending = 1 << 10,  // Disable ability to sort in the ascending direction.
    SwGuiTableColumnFlags_NoSortDescending = 1 << 11,  // Disable ability to sort in the descending direction.
    SwGuiTableColumnFlags_NoHeaderLabel = 1 << 12,  // TableHeadersRow() will not submit label for this column. Convenient for some small columns. Name will still appear in context menu.
    SwGuiTableColumnFlags_NoHeaderWidth = 1 << 13,  // Disable header text width contribution to automatic column width.
    SwGuiTableColumnFlags_PreferSortAscending = 1 << 14,  // Make the initial sort direction Ascending when first sorting on this column (default).
    SwGuiTableColumnFlags_PreferSortDescending = 1 << 15,  // Make the initial sort direction Descending when first sorting on this column.
    SwGuiTableColumnFlags_IndentEnable = 1 << 16,  // Use current Indent value when entering cell (default for column 0).
    SwGuiTableColumnFlags_IndentDisable = 1 << 17,  // Ignore current Indent value when entering cell (default for columns > 0). Indentation changes _within_ the cell will still be honored.

    // Output status flags, read-only via TableGetColumnFlags()
    SwGuiTableColumnFlags_IsEnabled = 1 << 24,  // Status: is enabled == not hidden by user/api (referred to as "Hide" in _DefaultHide and _NoHide) flags.
    SwGuiTableColumnFlags_IsVisible = 1 << 25,  // Status: is visible == is enabled AND not clipped by scrolling.
    SwGuiTableColumnFlags_IsSorted = 1 << 26,  // Status: is currently part of the sort specs
    SwGuiTableColumnFlags_IsHovered = 1 << 27,  // Status: is hovered by mouse

    // [Internal] Combinations and masks
    SwGuiTableColumnFlags_WidthMask_ = SwGuiTableColumnFlags_WidthStretch | SwGuiTableColumnFlags_WidthFixed,
    SwGuiTableColumnFlags_IndentMask_ = SwGuiTableColumnFlags_IndentEnable | SwGuiTableColumnFlags_IndentDisable,
    SwGuiTableColumnFlags_StatusMask_ = SwGuiTableColumnFlags_IsEnabled | SwGuiTableColumnFlags_IsVisible | SwGuiTableColumnFlags_IsSorted | SwGuiTableColumnFlags_IsHovered,
    SwGuiTableColumnFlags_NoDirectResize_ = 1 << 30,  // [Internal] Disable user resizing this column directly (it may however we resized indirectly from its left edge)

    // Obsolete names (will be removed soon)
#ifndef SW_DISABLE_OBSOLETE_FUNCTIONS
    //SwGuiTableColumnFlags_WidthAuto           = SwGuiTableColumnFlags_WidthFixed | SwGuiTableColumnFlags_NoResize, // Column will not stretch and keep resizing based on submitted contents.
#endif
};

// Flags for SW::TableNextRow()
enum SwGuiTableRowFlags_
{
    SwGuiTableRowFlags_None = 0,
    SwGuiTableRowFlags_Headers = 1 << 0,   // Identify header row (set default background color + width of its contents accounted differently for auto column width)
};

// Enum for SW::TableSetBgColor()
// Background colors are rendering in 3 layers:
//  - Layer 0: draw with RowBg0 color if set, otherwise draw with ColumnBg0 if set.
//  - Layer 1: draw with RowBg1 color if set, otherwise draw with ColumnBg1 if set.
//  - Layer 2: draw with CellBg color if set.
// The purpose of the two row/columns layers is to let you decide if a background color change should override or blend with the existing color.
// When using SwGuiTableFlags_RowBg on the table, each row has the RowBg0 color automatically set for odd/even rows.
// If you set the color of RowBg0 target, your color will override the existing RowBg0 color.
// If you set the color of RowBg1 or ColumnBg1 target, your color will blend over the RowBg0 color.
enum SwGuiTableBgTarget_
{
    SwGuiTableBgTarget_None = 0,
    SwGuiTableBgTarget_RowBg0 = 1,        // Set row background color 0 (generally used for background, automatically set when SwGuiTableFlags_RowBg is used)
    SwGuiTableBgTarget_RowBg1 = 2,        // Set row background color 1 (generally used for selection marking)
    SwGuiTableBgTarget_CellBg = 3,        // Set cell background color (top-most color)
};

// Flags for SW::IsWindowFocused()
enum SwGuiFocusedFlags_
{
    SwGuiFocusedFlags_None = 0,
    SwGuiFocusedFlags_ChildWindows = 1 << 0,   // Return true if any children of the window is focused
    SwGuiFocusedFlags_RootWindow = 1 << 1,   // Test from root window (top most parent of the current hierarchy)
    SwGuiFocusedFlags_AnyWindow = 1 << 2,   // Return true if any window is focused. Swportant: If you are trying to tell how to dispatch your low-level inputs, do NOT use this. Use 'io.WantCaptureMouse' instead! Please read the FAQ!
    SwGuiFocusedFlags_NoPopupHierarchy = 1 << 3,   // Do not consider popup hierarchy (do not treat popup emitter as parent of popup) (when used with _ChildWindows or _RootWindow)
    //SwGuiFocusedFlags_DockHierarchy               = 1 << 4,   // Consider docking hierarchy (treat dockspace host as parent of docked window) (when used with _ChildWindows or _RootWindow)
    SwGuiFocusedFlags_RootAndChildWindows = SwGuiFocusedFlags_RootWindow | SwGuiFocusedFlags_ChildWindows,
};

// Flags for SW::IsItemHovered(), SW::IsWindowHovered()
// Note: if you are trying to check whether your mouse should be dispatched to  SwGui or to your app, you should use 'io.WantCaptureMouse' instead! Please read the FAQ!
// Note: windows with the SwGuiWindowFlags_NoInputs flag are ignored by IsWindowHovered() calls.
enum SwGuiHoveredFlags_
{
    SwGuiHoveredFlags_None = 0,        // Return true if directly over the item/window, not obstructed by another window, not obstructed by an active popup or modal blocking inputs under them.
    SwGuiHoveredFlags_ChildWindows = 1 << 0,   // IsWindowHovered() only: Return true if any children of the window is hovered
    SwGuiHoveredFlags_RootWindow = 1 << 1,   // IsWindowHovered() only: Test from root window (top most parent of the current hierarchy)
    SwGuiHoveredFlags_AnyWindow = 1 << 2,   // IsWindowHovered() only: Return true if any window is hovered
    SwGuiHoveredFlags_NoPopupHierarchy = 1 << 3,   // IsWindowHovered() only: Do not consider popup hierarchy (do not treat popup emitter as parent of popup) (when used with _ChildWindows or _RootWindow)
    SwGuiHoveredFlags_DockHierarchy = 1 << 4,   // IsWindowHovered() only: Consider docking hierarchy (treat dockspace host as parent of docked window) (when used with _ChildWindows or _RootWindow)
    SwGuiHoveredFlags_AllowWhenBlockedByPopup = 1 << 5,   // Return true even if a popup window is normally blocking access to this item/window
    //SwGuiHoveredFlags_AllowWhenBlockedByModal     = 1 << 6,   // Return true even if a modal popup window is normally blocking access to this item/window. FIXME-TODO: Unavailable yet.
    SwGuiHoveredFlags_AllowWhenBlockedByActiveItem = 1 << 7,   // Return true even if an active item is blocking access to this item/window. Useful for Drag and Drop patterns.
    SwGuiHoveredFlags_AllowWhenOverlappedByItem = 1 << 8,   // IsItemHovered() only: Return true even if the item uses AllowOverlap mode and is overlapped by another hoverable item.
    SwGuiHoveredFlags_AllowWhenOverlappedByWindow = 1 << 9,   // IsItemHovered() only: Return true even if the position is obstructed or overlapped by another window.
    SwGuiHoveredFlags_AllowWhenDisabled = 1 << 10,  // IsItemHovered() only: Return true even if the item is disabled
    SwGuiHoveredFlags_NoNavOverride = 1 << 11,  // IsItemHovered() only: Disable using gamepad/keyboard navigation state when active, always query mouse
    SwGuiHoveredFlags_AllowWhenOverlapped = SwGuiHoveredFlags_AllowWhenOverlappedByItem | SwGuiHoveredFlags_AllowWhenOverlappedByWindow,
    SwGuiHoveredFlags_RectOnly = SwGuiHoveredFlags_AllowWhenBlockedByPopup | SwGuiHoveredFlags_AllowWhenBlockedByActiveItem | SwGuiHoveredFlags_AllowWhenOverlapped,
    SwGuiHoveredFlags_RootAndChildWindows = SwGuiHoveredFlags_RootWindow | SwGuiHoveredFlags_ChildWindows,

    // Tooltips mode
    // - typically used in IsItemHovered() + SetTooltip() sequence.
    // - this is a shortcut to pull flags from 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav' where you can reconfigure desired behavior.
    //   e.g. 'TooltipHoveredFlagsForMouse' defaults to 'SwGuiHoveredFlags_Stationary | SwGuiHoveredFlags_DelayShort'.
    // - for frequently actioned or hovered items providing a tooltip, you want may to use SwGuiHoveredFlags_ForTooltip (stationary + delay) so the tooltip doesn't show too often.
    // - for items which main purpose is to be hovered, or items with low affordance, or in less consistent apps, prefer no delay or shorter delay.
    SwGuiHoveredFlags_ForTooltip = 1 << 12,  // Shortcut for standard flags when using IsItemHovered() + SetTooltip() sequence.

    // (Advanced) Mouse Hovering delays.
    // - generally you can use SwGuiHoveredFlags_ForTooltip to use application-standardized flags.
    // - use those if you need specific overrides.
    SwGuiHoveredFlags_Stationary = 1 << 13,  // Require mouse to be stationary for style.HoverStationaryDelay (~0.15 sec) _at least one time_. After this, can move on same item/window. Using the stationary test tends to reduces the need for a long delay.
    SwGuiHoveredFlags_DelayNone = 1 << 14,  // IsItemHovered() only: Return true immediately (default). As this is the default you generally ignore this.
    SwGuiHoveredFlags_DelayShort = 1 << 15,  // IsItemHovered() only: Return true after style.HoverDelayShort elapsed (~0.15 sec) (shared between items) + requires mouse to be stationary for style.HoverStationaryDelay (once per item).
    SwGuiHoveredFlags_DelayNormal = 1 << 16,  // IsItemHovered() only: Return true after style.HoverDelayNormal elapsed (~0.40 sec) (shared between items) + requires mouse to be stationary for style.HoverStationaryDelay (once per item).
    SwGuiHoveredFlags_NoSharedDelay = 1 << 17,  // IsItemHovered() only: Disable shared delay system where moving from one item to the next keeps the previous timer for a short time (standard for tooltips with long delays)
};

// Flags for SW::DockSpace(), shared/inherited by child nodes.
// (Some flags can be applied to individual nodes directly)
// FIXME-DOCK: Also see SwGuiDockNodeFlagsPrivate_ which may involve using the WIP and internal DockBuilder api.
enum SwGuiDockNodeFlags_
{
    SwGuiDockNodeFlags_None = 0,
    SwGuiDockNodeFlags_KeepAliveOnly = 1 << 0,   //       // Don't display the dockspace node but keep it alive. Windows docked into this dockspace node won't be undocked.
    //SwGuiDockNodeFlags_NoCentralNode              = 1 << 1,   //       // Disable Central Node (the node which can stay empty)
    SwGuiDockNodeFlags_NoDockingOverCentralNode = 1 << 2,   //       // Disable docking over the Central Node, which will be always kept empty.
    SwGuiDockNodeFlags_PassthruCentralNode = 1 << 3,   //       // Enable passthru dockspace: 1) DockSpace() will render a SwGuiCol_WindowBg background covering everything excepted the Central Node when empty. Meaning the host window should probably use SetNextWindowBgAlpha(0.0f) prior to Begin() when using this. 2) When Central Node is empty: let inputs pass-through + won't display a DockingEmptyBg background. See demo for details.
    SwGuiDockNodeFlags_NoDockingSplit = 1 << 4,   //       // Disable other windows/nodes from splitting this node.
    SwGuiDockNodeFlags_NoResize = 1 << 5,   // Saved // Disable resizing node using the splitter/separators. Useful with programmatically setup dockspaces.
    SwGuiDockNodeFlags_AutoHideTabBar = 1 << 6,   //       // Tab bar will automatically hide when there is a single window in the dock node.
    SwGuiDockNodeFlags_NoUndocking = 1 << 7,   //       // Disable undocking this node.

#ifndef SW_DISABLE_OBSOLETE_FUNCTIONS
    SwGuiDockNodeFlags_NoSplit = SwGuiDockNodeFlags_NoDockingSplit, // Renamed in 1.90
    SwGuiDockNodeFlags_NoDockingInCentralNode = SwGuiDockNodeFlags_NoDockingOverCentralNode, // Renamed in 1.90
#endif
};

// Flags for SW::BeginDragDropSource(), SW::AcceptDragDropPayload()
enum SwGuiDragDropFlags_
{
    SwGuiDragDropFlags_None = 0,
    // BeginDragDropSource() flags
    SwGuiDragDropFlags_SourceNoPreviewTooltip = 1 << 0,   // By default, a successful call to BeginDragDropSource opens a tooltip so you can display a preview or description of the source contents. This flag disables this behavior.
    SwGuiDragDropFlags_SourceNoDisableHover = 1 << 1,   // By default, when dragging we clear data so that IsItemHovered() will return false, to avoid subsequent user code submitting tooltips. This flag disables this behavior so you can still call IsItemHovered() on the source item.
    SwGuiDragDropFlags_SourceNoHoldToOpenOthers = 1 << 2,   // Disable the behavior that allows to open tree nodes and collapsing header by holding over them while dragging a source item.
    SwGuiDragDropFlags_SourceAllowNullID = 1 << 3,   // Allow items such as Text(), Swage() that have no unique identifier to be used as drag source, by manufacturing a temporary identifier based on their window-relative position. This is extremely unusual within the  imgui ecosystem and so we made it explicit.
    SwGuiDragDropFlags_SourceExtern = 1 << 4,   // External source (from outside of  imgui), won't attempt to read current item/window info. Will always return true. Only one Extern source can be active simultaneously.
    SwGuiDragDropFlags_SourceAutoExpirePayload = 1 << 5,   // Automatically expire the payload if the source cease to be submitted (otherwise payloads are persisting while being dragged)
    // AcceptDragDropPayload() flags
    SwGuiDragDropFlags_AcceptBeforeDelivery = 1 << 10,  // AcceptDragDropPayload() will returns true even before the mouse button is released. You can then call IsDelivery() to test if the payload needs to be delivered.
    SwGuiDragDropFlags_AcceptNoDrawDefaultRect = 1 << 11,  // Do not draw the default highlight rectangle when hovering over target.
    SwGuiDragDropFlags_AcceptNoPreviewTooltip = 1 << 12,  // Request hiding the BeginDragDropSource tooltip from the BeginDragDropTarget site.
    SwGuiDragDropFlags_AcceptPeekOnly = SwGuiDragDropFlags_AcceptBeforeDelivery | SwGuiDragDropFlags_AcceptNoDrawDefaultRect, // For peeking ahead and inspecting the payload before delivery.
};

// Standard Drag and Drop payload types. You can define you own payload types using short strings. Types starting with '_' are defined by  SwGui.
#define SW_PAYLOAD_TYPE_COLOR_3F     "_COL3F"    // float[3]: Standard type for colors, without alpha. User code may use this type.
#define SW_PAYLOAD_TYPE_COLOR_4F     "_COL4F"    // float[4]: Standard type for colors. User code may use this type.

// A primary data type
enum SwGuiDataType_
{
    SwGuiDataType_S8,       // signed char / char (with sensible compilers)
    SwGuiDataType_U8,       // unsigned char
    SwGuiDataType_S16,      // short
    SwGuiDataType_U16,      // unsigned short
    SwGuiDataType_S32,      // int
    SwGuiDataType_U32,      // unsigned int
    SwGuiDataType_S64,      // long long / __int64
    SwGuiDataType_U64,      // unsigned long long / unsigned __int64
    SwGuiDataType_Float,    // float
    SwGuiDataType_Double,   // double
    SwGuiDataType_COUNT
};

// A cardinal direction
enum SwGuiDir_
{
    SwGuiDir_None = -1,
    SwGuiDir_Left = 0,
    SwGuiDir_Right = 1,
    SwGuiDir_Up = 2,
    SwGuiDir_Down = 3,
    SwGuiDir_COUNT
};

// A sorting direction
enum SwGuiSortDirection_
{
    SwGuiSortDirection_None = 0,
    SwGuiSortDirection_Ascending = 1,    // Ascending = 0->9, A->Z etc.
    SwGuiSortDirection_Descending = 2     // Descending = 9->0, Z->A etc.
};

// Keys value 0 to 511 are left unused as legacy native/opaque key values (< 1.87)
// Keys value >= 512 are named keys (>= 1.87)
enum SwGuiKey : int
{
    // Keyboard
    SwGuiKey_None = 0,
    SwGuiKey_Tab = 512,             // == SwGuiKey_NamedKey_BEGIN
    SwGuiKey_LeftArrow,
    SwGuiKey_RightArrow,
    SwGuiKey_UpArrow,
    SwGuiKey_DownArrow,
    SwGuiKey_PageUp,
    SwGuiKey_PageDown,
    SwGuiKey_Home,
    SwGuiKey_End,
    SwGuiKey_Insert,
    SwGuiKey_Delete,
    SwGuiKey_Backspace,
    SwGuiKey_Space,
    SwGuiKey_Enter,
    SwGuiKey_Escape,
    SwGuiKey_LeftCtrl, SwGuiKey_LeftShift, SwGuiKey_LeftAlt, SwGuiKey_LeftSuper,
    SwGuiKey_RightCtrl, SwGuiKey_RightShift, SwGuiKey_RightAlt, SwGuiKey_RightSuper,
    SwGuiKey_Menu,
    SwGuiKey_0, SwGuiKey_1, SwGuiKey_2, SwGuiKey_3, SwGuiKey_4, SwGuiKey_5, SwGuiKey_6, SwGuiKey_7, SwGuiKey_8, SwGuiKey_9,
    SwGuiKey_A, SwGuiKey_B, SwGuiKey_C, SwGuiKey_D, SwGuiKey_E, SwGuiKey_F, SwGuiKey_G, SwGuiKey_H, SwGuiKey_I, SwGuiKey_J,
    SwGuiKey_K, SwGuiKey_L, SwGuiKey_M, SwGuiKey_N, SwGuiKey_O, SwGuiKey_P, SwGuiKey_Q, SwGuiKey_R, SwGuiKey_S, SwGuiKey_T,
    SwGuiKey_U, SwGuiKey_V, SwGuiKey_W, SwGuiKey_X, SwGuiKey_Y, SwGuiKey_Z,
    SwGuiKey_F1, SwGuiKey_F2, SwGuiKey_F3, SwGuiKey_F4, SwGuiKey_F5, SwGuiKey_F6,
    SwGuiKey_F7, SwGuiKey_F8, SwGuiKey_F9, SwGuiKey_F10, SwGuiKey_F11, SwGuiKey_F12,
    SwGuiKey_F13, SwGuiKey_F14, SwGuiKey_F15, SwGuiKey_F16, SwGuiKey_F17, SwGuiKey_F18,
    SwGuiKey_F19, SwGuiKey_F20, SwGuiKey_F21, SwGuiKey_F22, SwGuiKey_F23, SwGuiKey_F24,
    SwGuiKey_Apostrophe,        // '
    SwGuiKey_Comma,             // ,
    SwGuiKey_Minus,             // -
    SwGuiKey_Period,            // .
    SwGuiKey_Slash,             // /
    SwGuiKey_Semicolon,         // ;
    SwGuiKey_Equal,             // =
    SwGuiKey_LeftBracket,       // [
    SwGuiKey_Backslash,         // \ (this text inhibit multiline comment caused by backslash)
    SwGuiKey_RightBracket,      // ]
    SwGuiKey_GraveAccent,       // `
    SwGuiKey_CapsLock,
    SwGuiKey_ScrollLock,
    SwGuiKey_NumLock,
    SwGuiKey_PrintScreen,
    SwGuiKey_Pause,
    SwGuiKey_Keypad0, SwGuiKey_Keypad1, SwGuiKey_Keypad2, SwGuiKey_Keypad3, SwGuiKey_Keypad4,
    SwGuiKey_Keypad5, SwGuiKey_Keypad6, SwGuiKey_Keypad7, SwGuiKey_Keypad8, SwGuiKey_Keypad9,
    SwGuiKey_KeypadDecimal,
    SwGuiKey_KeypadDivide,
    SwGuiKey_KeypadMultiply,
    SwGuiKey_KeypadSubtract,
    SwGuiKey_KeypadAdd,
    SwGuiKey_KeypadEnter,
    SwGuiKey_KeypadEqual,
    SwGuiKey_AppBack,               // Available on some keyboard/mouses. Often referred as "Browser Back"
    SwGuiKey_AppForward,

    // Gamepad (some of those are analog values, 0.0f to 1.0f)                          // NAVIGATION ACTION
    // (download controller mapping PNG/PSD at http://imgui.com/controls_sheets)
    SwGuiKey_GamepadStart,          // Menu (Xbox)      + (Switch)   Start/Options (PS)
    SwGuiKey_GamepadBack,           // View (Xbox)      - (Switch)   Share (PS)
    SwGuiKey_GamepadFaceLeft,       // X (Xbox)         Y (Switch)   Square (PS)        // Tap: Toggle Menu. Hold: Windowing mode (Focus/Move/Resize windows)
    SwGuiKey_GamepadFaceRight,      // B (Xbox)         A (Switch)   Circle (PS)        // Cancel / Close / Exit
    SwGuiKey_GamepadFaceUp,         // Y (Xbox)         X (Switch)   Triangle (PS)      // Text Input / On-screen Keyboard
    SwGuiKey_GamepadFaceDown,       // A (Xbox)         B (Switch)   Cross (PS)         // Activate / Open / Toggle / Tweak
    SwGuiKey_GamepadDpadLeft,       // D-pad Left                                       // Move / Tweak / Resize Window (in Windowing mode)
    SwGuiKey_GamepadDpadRight,      // D-pad Right                                      // Move / Tweak / Resize Window (in Windowing mode)
    SwGuiKey_GamepadDpadUp,         // D-pad Up                                         // Move / Tweak / Resize Window (in Windowing mode)
    SwGuiKey_GamepadDpadDown,       // D-pad Down                                       // Move / Tweak / Resize Window (in Windowing mode)
    SwGuiKey_GamepadL1,             // L Bumper (Xbox)  L (Switch)   L1 (PS)            // Tweak Slower / Focus Previous (in Windowing mode)
    SwGuiKey_GamepadR1,             // R Bumper (Xbox)  R (Switch)   R1 (PS)            // Tweak Faster / Focus Next (in Windowing mode)
    SwGuiKey_GamepadL2,             // L Trig. (Xbox)   ZL (Switch)  L2 (PS) [Analog]
    SwGuiKey_GamepadR2,             // R Trig. (Xbox)   ZR (Switch)  R2 (PS) [Analog]
    SwGuiKey_GamepadL3,             // L Stick (Xbox)   L3 (Switch)  L3 (PS)
    SwGuiKey_GamepadR3,             // R Stick (Xbox)   R3 (Switch)  R3 (PS)
    SwGuiKey_GamepadLStickLeft,     // [Analog]                                         // Move Window (in Windowing mode)
    SwGuiKey_GamepadLStickRight,    // [Analog]                                         // Move Window (in Windowing mode)
    SwGuiKey_GamepadLStickUp,       // [Analog]                                         // Move Window (in Windowing mode)
    SwGuiKey_GamepadLStickDown,     // [Analog]                                         // Move Window (in Windowing mode)
    SwGuiKey_GamepadRStickLeft,     // [Analog]
    SwGuiKey_GamepadRStickRight,    // [Analog]
    SwGuiKey_GamepadRStickUp,       // [Analog]
    SwGuiKey_GamepadRStickDown,     // [Analog]

    // Aliases: Mouse Buttons (auto-submitted from AddMouseButtonEvent() calls)
    // - This is mirroring the data also written to io.MouseDown[], io.MouseWheel, in a format allowing them to be accessed via standard key API.
    SwGuiKey_MouseLeft, SwGuiKey_MouseRight, SwGuiKey_MouseMiddle, SwGuiKey_MouseX1, SwGuiKey_MouseX2, SwGuiKey_MouseWheelX, SwGuiKey_MouseWheelY,

    // [Internal] Reserved for mod storage
    SwGuiKey_ReservedForModCtrl, SwGuiKey_ReservedForModShift, SwGuiKey_ReservedForModAlt, SwGuiKey_ReservedForModSuper,
    SwGuiKey_COUNT,

    // Keyboard Modifiers (explicitly submitted by backend via AddKeyEvent() calls)
    // - This is mirroring the data also written to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper, in a format allowing
    //   them to be accessed via standard key API, allowing calls such as IsKeyPressed(), IsKeyReleased(), querying duration etc.
    // - Code polling every key (e.g. an interface to detect a key press for input mapping) might want to ignore those
    //   and prefer using the real keys (e.g. SwGuiKey_LeftCtrl, SwGuiKey_RightCtrl instead of SwGuiMod_Ctrl).
    // - In theory the value of keyboard modifiers should be roughly equivalent to a logical or of the equivalent left/right keys.
    //   In practice: it's complicated; mods are often provided from different sources. Keyboard layout, IME, sticky keys and
    //   backends tend to interfere and break that equivalence. The safer decision is to relay that ambiguity down to the end-user...
    SwGuiMod_None = 0,
    SwGuiMod_Ctrl = 1 << 12, // Ctrl
    SwGuiMod_Shift = 1 << 13, // Shift
    SwGuiMod_Alt = 1 << 14, // Option/Menu
    SwGuiMod_Super = 1 << 15, // Cmd/Super/Windows
    SwGuiMod_Shortcut = 1 << 11, // Alias for Ctrl (non-macOS) _or_ Super (macOS).
    SwGuiMod_Mask_ = 0xF800,  // 5-bits

    // [Internal] Prior to 1.87 we required user to fill io.KeysDown[512] using their own native index + the io.KeyMap[] array.
    // We are ditching this method but keeping a legacy path for user code doing e.g. IsKeyPressed(MY_NATIVE_KEY_CODE)
    // If you need to iterate all keys (for e.g. an input mapper) you may use SwGuiKey_NamedKey_BEGIN..SwGuiKey_NamedKey_END.
    SwGuiKey_NamedKey_BEGIN = 512,
    SwGuiKey_NamedKey_END = SwGuiKey_COUNT,
    SwGuiKey_NamedKey_COUNT = SwGuiKey_NamedKey_END - SwGuiKey_NamedKey_BEGIN,
#ifdef SW_DISABLE_OBSOLETE_KEYIO
    SwGuiKey_KeysData_SIZE = SwGuiKey_NamedKey_COUNT,  // Size of KeysData[]: only hold named keys
    SwGuiKey_KeysData_OFFSET = SwGuiKey_NamedKey_BEGIN,  // Accesses to io.KeysData[] must use (key - SwGuiKey_KeysData_OFFSET) index.
#else
    SwGuiKey_KeysData_SIZE = SwGuiKey_COUNT,           // Size of KeysData[]: hold legacy 0..512 keycodes + named keys
    SwGuiKey_KeysData_OFFSET = 0,                        // Accesses to io.KeysData[] must use (key - SwGuiKey_KeysData_OFFSET) index.
#endif

#ifndef SW_DISABLE_OBSOLETE_FUNCTIONS
    SwGuiKey_ModCtrl = SwGuiMod_Ctrl, SwGuiKey_ModShift = SwGuiMod_Shift, SwGuiKey_ModAlt = SwGuiMod_Alt, SwGuiKey_ModSuper = SwGuiMod_Super, // Renamed in 1.89
    SwGuiKey_KeyPadEnter = SwGuiKey_KeypadEnter,    // Renamed in 1.87
#endif
};

// Helper "flags" version of key-mods to store and compare multiple key-mods easily. Sometimes used for storage (e.g. io.KeyMods) but otherwise not much used in public API.
enum SwGuiModFlags_
{
    SwGuiModFlags_None = 0,
    SwGuiModFlags_Ctrl = 1 << 0,
    SwGuiModFlags_Shift = 1 << 1,
    SwGuiModFlags_Alt = 1 << 2,   // Option/Menu key
    SwGuiModFlags_Super = 1 << 3,   // Cmd/Super/Windows key
    SwGuiModFlags_All = 0x0F
};

#ifndef SW_DISABLE_OBSOLETE_KEYIO
// OBSOLETED in 1.88 (from July 2022): SwGuiNavInput and io.NavInputs[].
// Official backends between 1.60 and 1.86: will keep working and feed gamepad inputs as long as SW_DISABLE_OBSOLETE_KEYIO is not set.
// Custom backends: feed gamepad inputs via io.AddKeyEvent() and SwGuiKey_GamepadXXX enums.
enum SwGuiNavInput
{
    SwGuiNavInput_Activate, SwGuiNavInput_Cancel, SwGuiNavInput_Input, SwGuiNavInput_Menu, SwGuiNavInput_DpadLeft, SwGuiNavInput_DpadRight, SwGuiNavInput_DpadUp, SwGuiNavInput_DpadDown,
    SwGuiNavInput_LStickLeft, SwGuiNavInput_LStickRight, SwGuiNavInput_LStickUp, SwGuiNavInput_LStickDown, SwGuiNavInput_FocusPrev, SwGuiNavInput_FocusNext, SwGuiNavInput_TweakSlow, SwGuiNavInput_TweakFast,
    SwGuiNavInput_COUNT,
};
#endif

// Configuration flags stored in io.ConfigFlags. Set by user/application.
enum SwGuiConfigFlags_
{
    SwGuiConfigFlags_None = 0,
    SwGuiConfigFlags_NavEnableKeyboard = 1 << 0,   // Master keyboard navigation enable flag.
    SwGuiConfigFlags_NavEnableGamepad = 1 << 1,   // Master gamepad navigation enable flag. Backend also needs to set SwGuiBackendFlags_HasGamepad.
    SwGuiConfigFlags_NavEnableSetMousePos = 1 << 2,   // Instruct navigation to move the mouse cursor. May be useful on TV/console systems where moving a virtual mouse is awkward. Will update io.MousePos and set io.WantSetMousePos=true. If enabled you MUST honor io.WantSetMousePos requests in your backend, otherwise SwGui will react as if the mouse is jumping around back and forth.
    SwGuiConfigFlags_NavNoCaptureKeyboard = 1 << 3,   // Instruct navigation to not set the io.WantCaptureKeyboard flag when io.NavActive is set.
    SwGuiConfigFlags_NoMouse = 1 << 4,   // Instruct imgui to clear mouse position/buttons in NewFrame(). This allows ignoring the mouse information set by the backend.
    SwGuiConfigFlags_NoMouseCursorChange = 1 << 5,   // Instruct backend to not alter mouse cursor shape and visibility. Use if the backend cursor changes are interfering with yours and you don't want to use SetMouseCursor() to change mouse cursor. You may want to honor requests from imgui by reading GetMouseCursor() yourself instead.

    // [BETA] Docking
    SwGuiConfigFlags_DockingEnable = 1 << 6,   // Docking enable flags.

    // [BETA] Viewports
    // When using viewports it is recommended that your default value for SwGuiCol_WindowBg is opaque (Alpha=1.0) so transition to a viewport won't be noticeable.
    SwGuiConfigFlags_ViewportsEnable = 1 << 10,  // Viewport enable flags (require both SwGuiBackendFlags_PlatformHasViewports + SwGuiBackendFlags_RendererHasViewports set by the respective backends)
    SwGuiConfigFlags_DpiEnableScaleViewports = 1 << 14,  // [BETA: Don't use] FIXME-DPI: Reposition and resize imgui windows when the DpiScale of a viewport changed (mostly useful for the main viewport hosting other window). Note that resizing the main window itself is up to your application.
    SwGuiConfigFlags_DpiEnableScaleFonts = 1 << 15,  // [BETA: Don't use] FIXME-DPI: Request bitmap-scaled fonts to match DpiScale. This is a very low-quality workaround. The correct way to handle DPI is _currently_ to replace the atlas and/or fonts in the Platform_OnChangedViewport callback, but this is all early work in progress.

    // User storage (to allow your backend/engine to communicate to code that may be shared between multiple projects. Those flags are NOT used by core  SwGui)
    SwGuiConfigFlags_IsSRGB = 1 << 20,  // Application is SRGB-aware.
    SwGuiConfigFlags_IsTouchScreen = 1 << 21,  // Application is using a touch screen instead of a mouse.
};

// Backend capabilities flags stored in io.BackendFlags. Set by mgui_impl_xxx or custom backend.
enum SwGuiBackendFlags_
{
    SwGuiBackendFlags_None = 0,
    SwGuiBackendFlags_HasGamepad = 1 << 0,   // Backend Platform supports gamepad and currently has one connected.
    SwGuiBackendFlags_HasMouseCursors = 1 << 1,   // Backend Platform supports honoring GetMouseCursor() value to change the OS cursor shape.
    SwGuiBackendFlags_HasSetMousePos = 1 << 2,   // Backend Platform supports io.WantSetMousePos requests to reposition the OS mouse position (only used if SwGuiConfigFlags_NavEnableSetMousePos is set).
    SwGuiBackendFlags_RendererHasVtxOffset = 1 << 3,   // Backend Renderer supports SwDrawCmd::VtxOffset. This enables output of large meshes (64K+ vertices) while still using 16-bit indices.

    // [BETA] Viewports
    SwGuiBackendFlags_PlatformHasViewports = 1 << 10,  // Backend Platform supports multiple viewports.
    SwGuiBackendFlags_HasMouseHoveredViewport = 1 << 11,  // Backend Platform supports calling io.AddMouseViewportEvent() with the viewport under the mouse. IF POSSIBLE, ignore viewports with the SwGuiViewportFlags_NoInputs flag (Win32 backend, GLFW 3.30+ backend can do this, SDL backend cannot). If this cannot be done,  SwGui needs to use a flawed heuristic to find the viewport under.
    SwGuiBackendFlags_RendererHasViewports = 1 << 12,  // Backend Renderer supports multiple viewports.
};

// Enumeration for PushStyleColor() / PopStyleColor()
enum SwGuiCol_
{
    SwGuiCol_Text,
    SwGuiCol_TextDisabled,
    SwGuiCol_WindowBg,              // Background of normal windows
    SwGuiCol_ChildBg,               // Background of child windows
    SwGuiCol_PopupBg,               // Background of popups, menus, tooltips windows
    SwGuiCol_Border,
    SwGuiCol_BorderShadow,
    SwGuiCol_FrameBg,               // Background of checkbox, radio button, plot, slider, text input
    SwGuiCol_FrameBgHovered,
    SwGuiCol_FrameBgActive,
    SwGuiCol_TitleBg,
    SwGuiCol_TitleBgActive,
    SwGuiCol_TitleBgCollapsed,
    SwGuiCol_MenuBarBg,
    SwGuiCol_ScrollbarBg,
    SwGuiCol_ScrollbarGrab,
    SwGuiCol_ScrollbarGrabHovered,
    SwGuiCol_ScrollbarGrabActive,
    SwGuiCol_CheckMark,
    SwGuiCol_SliderGrab,
    SwGuiCol_SliderGrabActive,
    SwGuiCol_Button,
    SwGuiCol_ButtonHovered,
    SwGuiCol_ButtonActive,
    SwGuiCol_Header,                // Header* colors are used for CollapsingHeader, TreeNode, Selectable, MenuItem
    SwGuiCol_HeaderHovered,
    SwGuiCol_HeaderActive,
    SwGuiCol_Separator,
    SwGuiCol_SeparatorHovered,
    SwGuiCol_SeparatorActive,
    SwGuiCol_ResizeGrip,            // Resize grip in lower-right and lower-left corners of windows.
    SwGuiCol_ResizeGripHovered,
    SwGuiCol_ResizeGripActive,
    SwGuiCol_Tab,                   // TabItem in a TabBar
    SwGuiCol_TabHovered,
    SwGuiCol_TabActive,
    SwGuiCol_TabUnfocused,
    SwGuiCol_TabUnfocusedActive,
    SwGuiCol_DockingPreview,        // Preview overlay color when about to docking something
    SwGuiCol_DockingEmptyBg,        // Background color for empty node (e.g. CentralNode with no window docked into it)
    SwGuiCol_PlotLines,
    SwGuiCol_PlotLinesHovered,
    SwGuiCol_PlotHistogram,
    SwGuiCol_PlotHistogramHovered,
    SwGuiCol_TableHeaderBg,         // Table header background
    SwGuiCol_TableBorderStrong,     // Table outer and header borders (prefer using Alpha=1.0 here)
    SwGuiCol_TableBorderLight,      // Table inner borders (prefer using Alpha=1.0 here)
    SwGuiCol_TableRowBg,            // Table row background (even rows)
    SwGuiCol_TableRowBgAlt,         // Table row background (odd rows)
    SwGuiCol_TextSelectedBg,
    SwGuiCol_DragDropTarget,        // Rectangle highlighting a drop target
    SwGuiCol_NavHighlight,          // Gamepad/keyboard: current highlighted item
    SwGuiCol_NavWindowingHighlight, // Highlight window when using CTRL+TAB
    SwGuiCol_NavWindowingDimBg,     // Darken/colorize entire screen behind the CTRL+TAB window list, when active
    SwGuiCol_ModalWindowDimBg,      // Darken/colorize entire screen behind a modal window, when one is active
    SwGuiCol_COUNT
};

// Enumeration for PushStyleVar() / PopStyleVar() to temporarily modify the SwGuiStyle structure.
// - The enum only refers to fields of SwGuiStyle which makes sense to be pushed/popped inside UI code.
//   During initialization or between frames, feel free to just poke into SwGuiStyle directly.
// - Tip: Use your programming IDE navigation facilities on the names in the _second column_ below to find the actual members and their description.
//   In Visual Studio IDE: CTRL+comma ("Edit.GoToAll") can follow symbols in comments, whereas CTRL+F12 ("Edit.GoToSwplementation") cannot.
//   With Visual Assist installed: ALT+G ("VAssistX.GoToSwplementation") can also follow symbols in comments.
// - When changing this enum, you need to update the associated internal table GStyleVarInfo[] accordingly. This is where we link enum values to members offset/type.
enum SwGuiStyleVar_
{
    // Enum name --------------------- // Member in SwGuiStyle structure (see SwGuiStyle for descriptions)
    SwGuiStyleVar_Alpha,               // float     Alpha
    SwGuiStyleVar_DisabledAlpha,       // float     DisabledAlpha
    SwGuiStyleVar_WindowPadding,       // SwVec2    WindowPadding
    SwGuiStyleVar_WindowRounding,      // float     WindowRounding
    SwGuiStyleVar_WindowBorderSize,    // float     WindowBorderSize
    SwGuiStyleVar_WindowMinSize,       // SwVec2    WindowMinSize
    SwGuiStyleVar_WindowTitleAlign,    // SwVec2    WindowTitleAlign
    SwGuiStyleVar_ChildRounding,       // float     ChildRounding
    SwGuiStyleVar_ChildBorderSize,     // float     ChildBorderSize
    SwGuiStyleVar_PopupRounding,       // float     PopupRounding
    SwGuiStyleVar_PopupBorderSize,     // float     PopupBorderSize
    SwGuiStyleVar_FramePadding,        // SwVec2    FramePadding
    SwGuiStyleVar_FrameRounding,       // float     FrameRounding
    SwGuiStyleVar_FrameBorderSize,     // float     FrameBorderSize
    SwGuiStyleVar_ItemSpacing,         // SwVec2    ItemSpacing
    SwGuiStyleVar_ItemInnerSpacing,    // SwVec2    ItemInnerSpacing
    SwGuiStyleVar_IndentSpacing,       // float     IndentSpacing
    SwGuiStyleVar_CellPadding,         // SwVec2    CellPadding
    SwGuiStyleVar_ScrollbarSize,       // float     ScrollbarSize
    SwGuiStyleVar_ScrollbarRounding,   // float     ScrollbarRounding
    SwGuiStyleVar_GrabMinSize,         // float     GrabMinSize
    SwGuiStyleVar_GrabRounding,        // float     GrabRounding
    SwGuiStyleVar_TabRounding,         // float     TabRounding
    SwGuiStyleVar_ButtonTextAlign,     // SwVec2    ButtonTextAlign
    SwGuiStyleVar_SelectableTextAlign, // SwVec2    SelectableTextAlign
    SwGuiStyleVar_COUNT
};

// Flags for InvisibleButton() [extended in mgui_internal.h]
enum SwGuiButtonFlags_
{
    SwGuiButtonFlags_None = 0,
    SwGuiButtonFlags_MouseButtonLeft = 1 << 0,   // React on left mouse button (default)
    SwGuiButtonFlags_MouseButtonRight = 1 << 1,   // React on right mouse button
    SwGuiButtonFlags_MouseButtonMiddle = 1 << 2,   // React on center mouse button

    // [Internal]
    SwGuiButtonFlags_MouseButtonMask_ = SwGuiButtonFlags_MouseButtonLeft | SwGuiButtonFlags_MouseButtonRight | SwGuiButtonFlags_MouseButtonMiddle,
    SwGuiButtonFlags_MouseButtonDefault_ = SwGuiButtonFlags_MouseButtonLeft,
};

// Flags for ColorEdit3() / ColorEdit4() / ColorPicker3() / ColorPicker4() / ColorButton()
enum SwGuiColorEditFlags_
{
    SwGuiColorEditFlags_None = 0,
    SwGuiColorEditFlags_NoAlpha = 1 << 1,   //              // ColorEdit, ColorPicker, ColorButton: ignore Alpha component (will only read 3 components from the input pointer).
    SwGuiColorEditFlags_NoPicker = 1 << 2,   //              // ColorEdit: disable picker when clicking on color square.
    SwGuiColorEditFlags_NoOptions = 1 << 3,   //              // ColorEdit: disable toggling options menu when right-clicking on inputs/small preview.
    SwGuiColorEditFlags_NoSmallPreview = 1 << 4,   //              // ColorEdit, ColorPicker: disable color square preview next to the inputs. (e.g. to show only the inputs)
    SwGuiColorEditFlags_NoInputs = 1 << 5,   //              // ColorEdit, ColorPicker: disable inputs sliders/text widgets (e.g. to show only the small preview color square).
    SwGuiColorEditFlags_NoTooltip = 1 << 6,   //              // ColorEdit, ColorPicker, ColorButton: disable tooltip when hovering the preview.
    SwGuiColorEditFlags_NoLabel = 1 << 7,   //              // ColorEdit, ColorPicker: disable display of inline text label (the label is still forwarded to the tooltip and picker).
    SwGuiColorEditFlags_NoSidePreview = 1 << 8,   //              // ColorPicker: disable bigger color preview on right side of the picker, use small color square preview instead.
    SwGuiColorEditFlags_NoDragDrop = 1 << 9,   //              // ColorEdit: disable drag and drop target. ColorButton: disable drag and drop source.
    SwGuiColorEditFlags_NoBorder = 1 << 10,  //              // ColorButton: disable border (which is enforced by default)

    // User Options (right-click on widget to change some of them).
    SwGuiColorEditFlags_AlphaBar = 1 << 16,  //              // ColorEdit, ColorPicker: show vertical alpha bar/gradient in picker.
    SwGuiColorEditFlags_AlphaPreview = 1 << 17,  //              // ColorEdit, ColorPicker, ColorButton: display preview as a transparent color over a checkerboard, instead of opaque.
    SwGuiColorEditFlags_AlphaPreviewHalf = 1 << 18,  //              // ColorEdit, ColorPicker, ColorButton: display half opaque / half checkerboard, instead of opaque.
    SwGuiColorEditFlags_HDR = 1 << 19,  //              // (WIP) ColorEdit: Currently only disable 0.0f..1.0f limits in RGBA edition (note: you probably want to use SwGuiColorEditFlags_Float flag as well).
    SwGuiColorEditFlags_DisplayRGB = 1 << 20,  // [Display]    // ColorEdit: override _display_ type among RGB/HSV/Hex. ColorPicker: select any combination using one or more of RGB/HSV/Hex.
    SwGuiColorEditFlags_DisplayHSV = 1 << 21,  // [Display]    // "
    SwGuiColorEditFlags_DisplayHex = 1 << 22,  // [Display]    // "
    SwGuiColorEditFlags_Uint8 = 1 << 23,  // [DataType]   // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0..255.
    SwGuiColorEditFlags_Float = 1 << 24,  // [DataType]   // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0.0f..1.0f floats instead of 0..255 integers. No round-trip of value via integers.
    SwGuiColorEditFlags_PickerHueBar = 1 << 25,  // [Picker]     // ColorPicker: bar for Hue, rectangle for Sat/Value.
    SwGuiColorEditFlags_PickerHueWheel = 1 << 26,  // [Picker]     // ColorPicker: wheel for Hue, triangle for Sat/Value.
    SwGuiColorEditFlags_InputRGB = 1 << 27,  // [Input]      // ColorEdit, ColorPicker: input and output data in RGB format.
    SwGuiColorEditFlags_InputHSV = 1 << 28,  // [Input]      // ColorEdit, ColorPicker: input and output data in HSV format.

    // Defaults Options. You can set application defaults using SetColorEditOptions(). The intent is that you probably don't want to
    // override them in most of your calls. Let the user choose via the option menu and/or call SetColorEditOptions() once during startup.
    SwGuiColorEditFlags_DefaultOptions_ = SwGuiColorEditFlags_Uint8 | SwGuiColorEditFlags_DisplayRGB | SwGuiColorEditFlags_InputRGB | SwGuiColorEditFlags_PickerHueBar,

    // [Internal] Masks
    SwGuiColorEditFlags_DisplayMask_ = SwGuiColorEditFlags_DisplayRGB | SwGuiColorEditFlags_DisplayHSV | SwGuiColorEditFlags_DisplayHex,
    SwGuiColorEditFlags_DataTypeMask_ = SwGuiColorEditFlags_Uint8 | SwGuiColorEditFlags_Float,
    SwGuiColorEditFlags_PickerMask_ = SwGuiColorEditFlags_PickerHueWheel | SwGuiColorEditFlags_PickerHueBar,
    SwGuiColorEditFlags_InputMask_ = SwGuiColorEditFlags_InputRGB | SwGuiColorEditFlags_InputHSV,

    // Obsolete names (will be removed)
    // SwGuiColorEditFlags_RGB = SwGuiColorEditFlags_DisplayRGB, SwGuiColorEditFlags_HSV = SwGuiColorEditFlags_DisplayHSV, SwGuiColorEditFlags_HEX = SwGuiColorEditFlags_DisplayHex  // [renamed in 1.69]
};

// Flags for DragFloat(), DragInt(), SliderFloat(), SliderInt() etc.
// We use the same sets of flags for DragXXX() and SliderXXX() functions as the features are the same and it makes it easier to swap them.
enum SwGuiSliderFlags_
{
    SwGuiSliderFlags_None = 0,
    SwGuiSliderFlags_AlwaysClamp = 1 << 4,       // Clamp value to min/max bounds when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds.
    SwGuiSliderFlags_Logarithmic = 1 << 5,       // Make the widget logarithmic (linear otherwise). Consider using SwGuiSliderFlags_NoRoundToFormat with this if using a format-string with small amount of digits.
    SwGuiSliderFlags_NoRoundToFormat = 1 << 6,       // Disable rounding underlying value to match precision of the display format string (e.g. %.3f values are rounded to those 3 digits)
    SwGuiSliderFlags_NoInput = 1 << 7,       // Disable CTRL+Click or Enter key allowing to input text directly into the widget
    SwGuiSliderFlags_InvalidMask_ = 0x7000000F,   // [Internal] We treat using those bits as being potentially a 'float power' argument from the previous API that has got miscast to this enum, and will trigger an assert if needed.

    // Obsolete names (will be removed)
#ifndef SW_DISABLE_OBSOLETE_FUNCTIONS
    SwGuiSliderFlags_ClampOnInput = SwGuiSliderFlags_AlwaysClamp, // [renamed in 1.79]
#endif
};

// Identify a mouse button.
// Those values are guaranteed to be stable and we frequently use 0/1 directly. Named enums provided for convenience.
enum SwGuiMouseButton_
{
    SwGuiMouseButton_Left = 0,
    SwGuiMouseButton_Right = 1,
    SwGuiMouseButton_Middle = 2,
    SwGuiMouseButton_COUNT = 5
};

// Enumeration for GetMouseCursor()
// User code may request backend to display given cursor by calling SetMouseCursor(), which is why we have some cursors that are marked unused here
enum SwGuiMouseCursor_
{
    SwGuiMouseCursor_None = -1,
    SwGuiMouseCursor_Arrow = 0,
    SwGuiMouseCursor_TextInput,         // When hovering over InputText, etc.
    SwGuiMouseCursor_ResizeAll,         // (Unused by  SwGui functions)
    SwGuiMouseCursor_ResizeNS,          // When hovering over a horizontal border
    SwGuiMouseCursor_ResizeEW,          // When hovering over a vertical border or a column
    SwGuiMouseCursor_ResizeNESW,        // When hovering over the bottom-left corner of a window
    SwGuiMouseCursor_ResizeNWSE,        // When hovering over the bottom-right corner of a window
    SwGuiMouseCursor_Hand,              // (Unused by  SwGui functions. Use for e.g. hyperlinks)
    SwGuiMouseCursor_NotAllowed,        // When hovering something with disallowed interaction. Usually a crossed circle.
    SwGuiMouseCursor_COUNT
};

// Enumeration for AddMouseSourceEvent() actual source of Mouse Input data.
// Historically we use "Mouse" terminology everywhere to indicate pointer data, e.g. MousePos, IsMousePressed(), io.AddMousePosEvent()
// But that "Mouse" data can come from different source which occasionally may be useful for application to know about.
// You can submit a change of pointer type using io.AddMouseSourceEvent().
enum SwGuiMouseSource : int
{
    SwGuiMouseSource_Mouse = 0,         // Input is coming from an actual mouse.
    SwGuiMouseSource_TouchScreen,       // Input is coming from a touch screen (no hovering prior to initial press, less precise initial press aiming, dual-axis wheeling possible).
    SwGuiMouseSource_Pen,               // Input is coming from a pressure/magnetic pen (often used in conjunction with high-sampling rates).
    SwGuiMouseSource_COUNT
};

// Enumeration for SW::SetWindow***(), SetNextWindow***(), SetNextItem***() functions
// Represent a condition.
// Swportant: Treat as a regular enum! Do NOT combine multiple values using binary operators! All the functions above treat 0 as a shortcut to SwGuiCond_Always.
enum SwGuiCond_
{
    SwGuiCond_None = 0,        // No condition (always set the variable), same as _Always
    SwGuiCond_Always = 1 << 0,   // No condition (always set the variable), same as _None
    SwGuiCond_Once = 1 << 1,   // Set the variable once per runtime session (only the first call will succeed)
    SwGuiCond_FirstUseEver = 1 << 2,   // Set the variable if the object/window has no persistently saved data (no entry in .ini file)
    SwGuiCond_Appearing = 1 << 3,   // Set the variable if the object/window is appearing after being hidden/inactive (or the first time)
};


//-----------------------------------------------------------------------------
// [SECTION] SwGuiStyle
//-----------------------------------------------------------------------------
// You may modify the SW::GetStyle() main instance during initialization and before NewFrame().
// During the frame, use SW::PushStyleVar(SwGuiStyleVar_XXXX)/PopStyleVar() to alter the main style values,
// and SW::PushStyleColor(SwGuiCol_XXX)/PopStyleColor() for colors.
//-----------------------------------------------------------------------------

struct SwGuiStyle
{
    float       Alpha;                      // Global alpha applies to everything in  SwGui.
    float       DisabledAlpha;              // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha.
    SwVec2      WindowPadding;              // Padding within a window.
    float       WindowRounding;             // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended.
    float       WindowBorderSize;           // Thickness of border around windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly).
    SwVec2      WindowMinSize;              // Swmum window size. This is a global setting. If you want to constrain individual windows, use SetNextWindowSizeConstraints().
    SwVec2      WindowTitleAlign;           // Alignment for title bar text. Defaults to (0.0f,0.5f) for left-aligned,vertically centered.
    SwGuiDir    WindowMenuButtonPosition;   // Side of the collapsing/docking button in the title bar (None/Left/Right). Defaults to SwGuiDir_Left.
    float       ChildRounding;              // Radius of child window corners rounding. Set to 0.0f to have rectangular windows.
    float       ChildBorderSize;            // Thickness of border around child windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly).
    float       PopupRounding;              // Radius of popup window corners rounding. (Note that tooltip windows use WindowRounding)
    float       PopupBorderSize;            // Thickness of border around popup/tooltip windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly).
    SwVec2      FramePadding;               // Padding within a framed rectangle (used by most widgets).
    float       FrameRounding;              // Radius of frame corners rounding. Set to 0.0f to have rectangular frame (used by most widgets).
    float       FrameBorderSize;            // Thickness of border around frames. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly).
    SwVec2      ItemSpacing;                // Horizontal and vertical spacing between widgets/lines.
    SwVec2      ItemInnerSpacing;           // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label).
    SwVec2      CellPadding;                // Padding within a table cell. CellPadding.y may be altered between different rows.
    SwVec2      TouchExtraPadding;          // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
    float       IndentSpacing;              // Horizontal indentation when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
    float       ColumnsMinSpacing;          // Swmum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
    float       ScrollbarSize;              // Width of the vertical scrollbar, Height of the horizontal scrollbar.
    float       ScrollbarRounding;          // Radius of grab corners for scrollbar.
    float       GrabMinSize;                // Swmum width/height of a grab box for slider/scrollbar.
    float       GrabRounding;               // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
    float       LogSliderDeadzone;          // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
    float       TabRounding;                // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
    float       TabBorderSize;              // Thickness of border around tabs.
    float       TabMinWidthForCloseButton;  // Swmum width for close button to appear on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected.
    float       TabBarBorderSize;           // Thickness of tab-bar separator, which takes on the tab active color to denote focus.
    float       TableAngledHeadersAngle;    // Angle of angled headers (supported values range from -50.0f degrees to +50.0f degrees).
    SwGuiDir    ColorButtonPosition;        // Side of the color button in the ColorEdit4 widget (left/right). Defaults to SwGuiDir_Right.
    SwVec2      ButtonTextAlign;            // Alignment of button text when button is larger than text. Defaults to (0.5f, 0.5f) (centered).
    SwVec2      SelectableTextAlign;        // Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line.
    float       SeparatorTextBorderSize;    // Thickkness of border in SeparatorText()
    SwVec2      SeparatorTextAlign;         // Alignment of text within the separator. Defaults to (0.0f, 0.5f) (left aligned, center).
    SwVec2      SeparatorTextPadding;       // Horizontal offset of text from each edge of the separator + spacing on other axis. Generally small values. .y is recommended to be == FramePadding.y.
    SwVec2      DisplayWindowPadding;       // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows.
    SwVec2      DisplaySafeAreaPadding;     // If you cannot see the edges of your screen (e.g. on a TV) increase the safe area padding. Apply to popups/tooltips as well regular windows. NB: Prefer configuring your TV sets correctly!
    float       DockingSeparatorSize;       // Thickness of resizing border between docked windows
    float       MouseCursorScale;           // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). We apply per-monitor DPI scaling over this scale. May be removed later.
    bool        AntiAliasedLines;           // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to SwDrawList).
    bool        AntiAliasedLinesUseTex;     // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering). Latched at the beginning of the frame (copied to SwDrawList).
    bool        AntiAliasedFill;            // Enable anti-aliased edges around filled shapes (rounded rectangles, circles, etc.). Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to SwDrawList).
    float       CurveTessellationTol;       // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
    float       CircleTessellationMaxError; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry.
    SwVec4      Colors[SwGuiCol_COUNT];

    // Behaviors
    // (It is possible to modify those fields mid-frame if specific behavior need it, unlike e.g. configuration fields in SwGuiIO)
    float             HoverStationaryDelay;     // Delay for IsItemHovered(SwGuiHoveredFlags_Stationary). Time required to consider mouse stationary.
    float             HoverDelayShort;          // Delay for IsItemHovered(SwGuiHoveredFlags_DelayShort). Usually used along with HoverStationaryDelay.
    float             HoverDelayNormal;         // Delay for IsItemHovered(SwGuiHoveredFlags_DelayNormal). "
    SwGuiHoveredFlags HoverFlagsForTooltipMouse;// Default flags when using IsItemHovered(SwGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using mouse.
    SwGuiHoveredFlags HoverFlagsForTooltipNav;  // Default flags when using IsItemHovered(SwGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using keyboard/gamepad.

    SW_API SwGuiStyle();
    SW_API void ScaleAllSizes(float scale_factor);
};


//-----------------------------------------------------------------------------
// [SECTION] SwGuiIO
//-----------------------------------------------------------------------------
// Communicate most settings and inputs/outputs to  SwGui using this structure.
// Access via SW::GetIO(). Read 'Programmer guide' section in .cpp file for general usage.
//-----------------------------------------------------------------------------

// [Internal] Storage used by IsKeyDown(), IsKeyPressed() etc functions.
// If prior to 1.87 you used io.KeysDownDuration[] (which was marked as internal), you should use GetKeyData(key)->DownDuration and not io.KeysData[key]->DownDuration.
struct SwGuiKeyData
{
    bool                    Down;               // True for if key is down
    float                   DownDuration;       // Duration the key has been down (<0.0f: not pressed, 0.0f: just pressed, >0.0f: time held)
    float                   DownDurationPrev;   // Last frame duration the key has been down
    float                   AnalogValue;        // 0.0f..1.0f for gamepad values
};

struct SwGuiIO
{
    //------------------------------------------------------------------
    // Configuration                            // Default value
    //------------------------------------------------------------------

    SwGuiConfigFlags        ConfigFlags;             // = 0              // See SwGuiConfigFlags_ enum. Set by user/application. Gamepad/keyboard navigation options, etc.
    SwGuiBackendFlags       BackendFlags;            // = 0              // See SwGuiBackendFlags_ enum. Set by backend (mgui_impl_xxx files or custom backend) to communicate features supported by the backend.
    SwVec2                  DisplaySize;                    // <unset>          // Main display size, in pixels (generally == GetMainViewport()->Size). May change every frame.
    float                   DeltaTime;                      // = 1.0f/60.0f     // Time elapsed since last frame, in seconds. May change every frame.
    float                   IniSavingRate;                  // = 5.0f           // Swmum time between saving positions/sizes to .ini file, in seconds.
    const char*             IniFilename;                    // = "imgui.ini"    // Path to .ini file (important: default "imgui.ini" is relative to current working dir!). Set NULL to disable automatic .ini loading/saving or if you want to manually call LoadIniSettingsXXX() / SaveIniSettingsXXX() functions.
    const char*             LogFilename;                    // = "mgui_log.txt"// Path to .log file (default parameter to SW::LogToFile when no file is specified).
    void*                   UserData;                       // = NULL           // Store your own data.

    SwFontAtlas*            Fonts;                          // <auto>           // Font atlas: load, rasterize and pack one or more fonts into a single texture.
    float                   FontGlobalScale;                // = 1.0f           // Global scale all fonts
    bool                    FontAllowUserScaling;           // = false          // Allow user scaling text of individual window with CTRL+Wheel.
    SwFont*                 FontDefault;                    // = NULL           // Font to use on NewFrame(). Use NULL to uses Fonts->Fonts[0].
    SwVec2                  DisplayFramebufferScale;        // = (1, 1)         // For retina display or other situations where window coordinates are different from framebuffer coordinates. This generally ends up in SwDrawData::FramebufferScale.

    // Docking options (when SwGuiConfigFlags_DockingEnable is set)
    bool                    ConfigDockingNoSplit;           // = false          // Simplified docking mode: disable window splitting, so docking is limited to merging multiple windows together into tab-bars.
    bool                    ConfigDockingWithShift;         // = false          // Enable docking with holding Shift key (reduce visual noise, allows dropping in wider space)
    bool                    ConfigDockingAlwaysTabBar;      // = false          // [BETA] [FIXME: This currently creates regression with auto-sizing and general overhead] Make every single floating window display within a docking node.
    bool                    ConfigDockingTransparentPayload;// = false          // [BETA] Make window or viewport transparent when docking and only display docking boxes on the target viewport. Useful if rendering of multiple viewport cannot be synced. Best used with ConfigViewportsNoAutoMerge.

    // Viewport options (when SwGuiConfigFlags_ViewportsEnable is set)
    bool                    ConfigViewportsNoAutoMerge;     // = false;         // Set to make all floating imgui windows always create their own viewport. Otherwise, they are merged into the main host viewports when overlapping it. May also set SwGuiViewportFlags_NoAutoMerge on individual viewport.
    bool                    ConfigViewportsNoTaskBarIcon;   // = false          // Disable default OS task bar icon flag for secondary viewports. When a viewport doesn't want a task bar icon, SwGuiViewportFlags_NoTaskBarIcon will be set on it.
    bool                    ConfigViewportsNoDecoration;    // = true           // Disable default OS window decoration flag for secondary viewports. When a viewport doesn't want window decorations, SwGuiViewportFlags_NoDecoration will be set on it. Enabling decoration can create subsequent issues at OS levels (e.g. minimum window size).
    bool                    ConfigViewportsNoDefaultParent; // = false          // Disable default OS parenting to main viewport for secondary viewports. By default, viewports are marked with ParentViewportId = <main_viewport>, expecting the platform backend to setup a parent/child relationship between the OS windows (some backend may ignore this). Set to true if you want the default to be 0, then all viewports will be top-level OS windows.

    // Miscellaneous options
    bool                    MouseDrawCursor;                // = false          // Request SwGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor). Cannot be easily renamed to 'io.ConfigXXX' because this is frequently used by backend implementations.
    bool                    ConfigMacOSXBehaviors;          // = defined(__APPLE__) // OS X style: Text editing cursor movement using Alt instead of Ctrl, Shortcuts using Cmd/Super instead of Ctrl, Line/Text Start and End using Cmd+Arrows instead of Home/End, Double click selects by word instead of selecting whole text, Multi-selection in lists uses Cmd/Super instead of Ctrl.
    bool                    ConfigInputTrickleEventQueue;   // = true           // Enable input queue trickling: some types of events submitted during the same frame (e.g. button down + up) will be spread over multiple frames, improving interactions with low framerates.
    bool                    ConfigInputTextCursorBlink;     // = true           // Enable blinking cursor (optional as some users consider it to be distracting).
    bool                    ConfigInputTextEnterKeepActive; // = false          // [BETA] Pressing Enter will keep item active and select contents (single-line only).
    bool                    ConfigDragClickToInputText;     // = false          // [BETA] Enable turning DragXXX widgets into text input with a simple mouse click-release (without moving). Not desirable on devices without a keyboard.
    bool                    ConfigWindowsResizeFromEdges;   // = true           // Enable resizing of windows from their edges and from the lower-left corner. This requires (io.BackendFlags & SwGuiBackendFlags_HasMouseCursors) because it needs mouse cursor feedback. (This used to be a per-window SwGuiWindowFlags_ResizeFromAnySide flag)
    bool                    ConfigWindowsMoveFromTitleBarOnly; // = false       // Enable allowing to move windows only when clicking on their title bar. Does not apply to windows without a title bar.
    float                   ConfigMemoryCompactTimer;       // = 60.0f          // Timer (in seconds) to free transient windows/tables memory buffers when unused. Set to -1.0f to disable.

    // Inputs Behaviors
    // (other variables, ones which are expected to be tweaked within UI code, are exposed in SwGuiStyle)
    float                   MouseDoubleClickTime;           // = 0.30f          // Time for a double-click, in seconds.
    float                   MouseDoubleClickMaxDist;        // = 6.0f           // Distance threshold to stay in to validate a double-click, in pixels.
    float                   MouseDragThreshold;             // = 6.0f           // Distance threshold before considering we are dragging.
    float                   KeyRepeatDelay;                 // = 0.275f         // When holding a key/button, time before it starts repeating, in seconds (for buttons in Repeat mode, etc.).
    float                   KeyRepeatRate;                  // = 0.050f         // When holding a key/button, rate at which it repeats, in seconds.

    //------------------------------------------------------------------
    // Debug options
    //------------------------------------------------------------------

    // Tools to test correct Begin/End and BeginChild/EndChild behaviors.
    // Presently Begin()/End() and BeginChild()/EndChild() needs to ALWAYS be called in tandem, regardless of return value of BeginXXX()
    // This is inconsistent with other BeginXXX functions and create confusion for many users.
    // We expect to update the API eventually. In the meanwhile we provide tools to facilitate checking user-code behavior.
    bool                    ConfigDebugBeginReturnValueOnce;// = false          // First-time calls to Begin()/BeginChild() will return false. NEEDS TO BE SET AT APPLICATION BOOT TIME if you don't want to miss windows.
    bool                    ConfigDebugBeginReturnValueLoop;// = false          // Some calls to Begin()/BeginChild() will return false. Will cycle through window depths then repeat. Suggested use: add "io.ConfigDebugBeginReturnValue = io.KeyShift" in your main loop then occasionally press SHIFT. Windows should be flickering while running.

    // Option to deactivate io.AddFocusEvent(false) handling. May facilitate interactions with a debugger when focus loss leads to clearing inputs data.
    // Backends may have other side-effects on focus loss, so this will reduce side-effects but not necessary remove all of them.
    // Consider using e.g. Win32's IsDebuggerPresent() as an additional filter (or see ImOsIsDebuggerPresent() in mgui_test_engine/mgui_te_utils.cpp for a Unix compatible version).
    bool                    ConfigDebugIgnoreFocusLoss;     // = false          // Ignore io.AddFocusEvent(false), consequently not calling io.ClearInputKeys() in input processing.

    // Option to audit .ini data
    bool                    ConfigDebugIniSettings;         // = false          // Save .ini data with extra comments (particularly helpful for Docking, but makes saving slower)

    //------------------------------------------------------------------
    // Platform Functions
    // (the mgui_impl_xxxx backend files are setting those up for you)
    //------------------------------------------------------------------

    // Optional: Platform/Renderer backend name (informational only! will be displayed in About Window) + User data for backend/wrappers to store their own stuff.
    const char*             BackendPlatformName;            // = NULL
    const char*             BackendRendererName;            // = NULL
    void*                   BackendPlatformUserData;        // = NULL           // User data for platform backend
    void*                   BackendRendererUserData;        // = NULL           // User data for renderer backend
    void*                   BackendLanguageUserData;        // = NULL           // User data for non C++ programming language backend

    // Optional: Access OS clipboard
    // (default to use native Win32 clipboard on Windows, otherwise uses a private clipboard. Override to access OS clipboard on other architectures)
    const char*             (*GetClipboardTextFn)(void* user_data);
    void                    (*SetClipboardTextFn)(void* user_data, const char* text);
    void*                   ClipboardUserData;

    // Optional: Notify OS Input Method Editor of the screen position of your cursor for text input position (e.g. when using Japanese/Chinese IME on Windows)
    // (default to use native imm32 api on Windows)
    void                    (*SetPlatformImeDataFn)(SwGuiViewport* viewport, SwGuiPlatformImeData* data);

    // Optional: Platform locale
    SwWchar                 PlatformLocaleDecimalPoint;     // '.'              // [Experimental] Configure decimal point e.g. '.' or ',' useful for some languages (e.g. German), generally pulled from *localeconv()->decimal_point

    //------------------------------------------------------------------
    // Input - Call before calling NewFrame()
    //------------------------------------------------------------------

    // Input Functions
    SW_API void  AddKeyEvent(SwGuiKey key, bool down);                   // Queue a new key down/up event. Key should be "translated" (as in, generally SwGuiKey_A matches the key end-user would use to emit an 'A' character)
    SW_API void  AddKeyAnalogEvent(SwGuiKey key, bool down, float v);    // Queue a new key down/up event for analog values (e.g. SwGuiKey_Gamepad_ values). Dead-zones should be handled by the backend.
    SW_API void  AddMousePosEvent(float x, float y);                     // Queue a mouse position update. Use -FLT_MAX,-FLT_MAX to signify no mouse (e.g. app not focused and not hovered)
    SW_API void  AddMouseButtonEvent(int button, bool down);             // Queue a mouse button change
    SW_API void  AddMouseWheelEvent(float wheel_x, float wheel_y);       // Queue a mouse wheel update. wheel_y<0: scroll down, wheel_y>0: scroll up, wheel_x<0: scroll right, wheel_x>0: scroll left.
    SW_API void  AddMouseSourceEvent(SwGuiMouseSource source);           // Queue a mouse source change (Mouse/TouchScreen/Pen)
    SW_API void  AddMouseViewportEvent(SwGuiID id);                      // Queue a mouse hovered viewport. Requires backend to set SwGuiBackendFlags_HasMouseHoveredViewport to call this (for multi-viewport support).
    SW_API void  AddFocusEvent(bool focused);                            // Queue a gain/loss of focus for the application (generally based on OS/platform focus of your window)
    SW_API void  AddInputCharacter(unsigned int c);                      // Queue a new character input
    SW_API void  AddInputCharacterUTF16(SwWchar16 c);                    // Queue a new character input from a UTF-16 character, it can be a surrogate
    SW_API void  AddInputCharactersUTF8(const char* str);                // Queue a new characters input from a UTF-8 string

    SW_API void  SetKeyEventNativeData(SwGuiKey key, int native_keycode, int native_scancode, int native_legacy_index = -1); // [Optional] Specify index for legacy <1.87 IsKeyXXX() functions with native indices + specify native keycode, scancode.
    SW_API void  SetAppAcceptingEvents(bool accepting_events);           // Set master flag for accepting key/mouse/text events (default to true). Useful if you have native dialog boxes that are interrupting your application loop/refresh, and you want to disable events being queued while your app is frozen.
    SW_API void  ClearEventsQueue();                                     // Clear all incoming events.
    SW_API void  ClearInputKeys();                                       // Clear current keyboard/mouse/gamepad state + current frame text input buffer. Equivalent to releasing all keys/buttons.
#ifndef SW_DISABLE_OBSOLETE_FUNCTIONS
    SW_API void  ClearInputCharacters();                                 // [Obsolete] Clear the current frame text input buffer. Now included within ClearInputKeys().
#endif

    //------------------------------------------------------------------
    // Output - Updated by NewFrame() or EndFrame()/Render()
    // (when reading from the io.WantCaptureMouse, io.WantCaptureKeyboard flags to dispatch your inputs, it is
    //  generally easier and more correct to use their state BEFORE calling NewFrame(). See FAQ for details!)
    //------------------------------------------------------------------

    bool                 WantCaptureMouse;                   // Set when  SwGui will use mouse inputs, in this case do not dispatch them to your main game/application (either way, always pass on mouse inputs to imgui). (e.g. unclicked mouse is hovering over an imgui window, widget is active, mouse was clicked over an imgui window, etc.).
    bool                 WantCaptureKeyboard;                // Set when  SwGui will use keyboard inputs, in this case do not dispatch them to your main game/application (either way, always pass keyboard inputs to imgui). (e.g. InputText active, or an imgui window is focused and navigation is enabled, etc.).
    bool                 WantTextInput;                      // Mobile/console: when set, you may display an on-screen keyboard. This is set by  SwGui when it wants textual keyboard input to happen (e.g. when a InputText widget is active).
    bool                 WantSetMousePos;                    // MousePos has been altered, backend should reposition mouse on next frame. Rarely used! Set only when SwGuiConfigFlags_NavEnableSetMousePos flag is enabled.
    bool                 WantSaveIniSettings;                // When manual .ini load/save is active (io.IniFilename == NULL), this will be set to notify your application that you can call SaveIniSettingsToMemory() and save yourself. Important: clear io.WantSaveIniSettings yourself after saving!
    bool                 NavActive;                          // Keyboard/Gamepad navigation is currently allowed (will handle SwGuiKey_NavXXX events) = a window is focused and it doesn't use the SwGuiWindowFlags_NoNavInputs flag.
    bool                 NavVisible;                         // Keyboard/Gamepad navigation is visible and allowed (will handle SwGuiKey_NavXXX events).
    float                Framerate;                          // Estimate of application framerate (rolling average over 60 frames, based on io.DeltaTime), in frame per second. Solely for convenience. Slow applications may not want to use a moving average or may want to reset underlying buffers occasionally.
    int                  MetricsRenderVertices;              // Vertices output during last call to Render()
    int                  MetricsRenderIndices;               // Indices output during last call to Render() = number of triangles * 3
    int                  MetricsRenderWindows;               // Number of visible windows
    int                  MetricsActiveWindows;               // Number of active windows
    SwVec2               MouseDelta;                         // Mouse delta. Note that this is zero if either current or previous position are invalid (-FLT_MAX,-FLT_MAX), so a disappearing/reappearing mouse won't have a huge delta.

    // Legacy: before 1.87, we required backend to fill io.KeyMap[] (imgui->native map) during initialization and io.KeysDown[] (native indices) every frame.
    // This is still temporarily supported as a legacy feature. However the new preferred scheme is for backend to call io.AddKeyEvent().
    //   Old (<1.87):  SW::IsKeyPressed(SW::GetIO().KeyMap[SwGuiKey_Space]) --> New (1.87+) SW::IsKeyPressed(SwGuiKey_Space)
#ifndef SW_DISABLE_OBSOLETE_KEYIO
    int                  KeyMap[SwGuiKey_COUNT];             // [LEGACY] Input: map of indices into the KeysDown[512] entries array which represent your "native" keyboard state. The first 512 are now unused and should be kept zero. Legacy backend will write into KeyMap[] using SwGuiKey_ indices which are always >512.
    bool                 KeysDown[SwGuiKey_COUNT];           // [LEGACY] Input: Keyboard keys that are pressed (ideally left in the "native" order your engine has access to keyboard keys, so you can use your own defines/enums for keys). This used to be [512] sized. It is now SwGuiKey_COUNT to allow legacy io.KeysDown[GetKeyIndex(...)] to work without an overflow.
    float                NavInputs[SwGuiNavInput_COUNT];     // [LEGACY] Since 1.88, NavInputs[] was removed. Backends from 1.60 to 1.86 won't build. Feed gamepad inputs via io.AddKeyEvent() and SwGuiKey_GamepadXXX enums.
#endif
#ifndef SW_DISABLE_OBSOLETE_FUNCTIONS
    void* ImeWindowHandle;                    // = NULL   // [Obsoleted in 1.87] Set SwGuiViewport::PlatformHandleRaw instead. Set this to your HWND to get automatic IME cursor positioning.
#else
    void* _UnusedPadding;
#endif

    //------------------------------------------------------------------
    // [Internal]  SwGui will maintain those fields. Forward compatibility not guaranteed!
    //------------------------------------------------------------------

    SwGuiContext*       Ctx;                              // Parent UI context (needs to be set explicitly by parent).

    // Main Input State
    // (this block used to be written by backend, since 1.87 it is best to NOT write to those directly, call the AddXXX functions above instead)
    // (reading from those variables is fair game, as they are extremely unlikely to be moving anywhere)
    SwVec2              MousePos;                           // Mouse position, in pixels. Set to SwVec2(-FLT_MAX, -FLT_MAX) if mouse is unavailable (on another screen, etc.)
    bool                MouseDown[5];                       // Mouse buttons: 0=left, 1=right, 2=middle + extras (SwGuiMouseButton_COUNT == 5).  SwGui mostly uses left and right buttons. Other buttons allow us to track if the mouse is being used by your application + available to user as a convenience via IsMouse** API.
    float               MouseWheel;                         // Mouse wheel Vertical: 1 unit scrolls about 5 lines text. >0 scrolls Up, <0 scrolls Down. Hold SHIFT to turn vertical scroll into horizontal scroll.
    float               MouseWheelH;                        // Mouse wheel Horizontal. >0 scrolls Left, <0 scrolls Right. Most users don't have a mouse with a horizontal wheel, may not be filled by all backends.
    SwGuiMouseSource    MouseSource;                   // Mouse actual input peripheral (Mouse/TouchScreen/Pen).
    SwGuiID             MouseHoveredViewport;               // (Optional) Modify using io.AddMouseViewportEvent(). With multi-viewports: viewport the OS mouse is hovering. If possible _IGNORING_ viewports with the SwGuiViewportFlags_NoInputs flag is much better (few backends can handle that). Set io.BackendFlags |= SwGuiBackendFlags_HasMouseHoveredViewport if you can provide this info. If you don't imgui will infer the value using the rectangles and last focused time of the viewports it knows about (ignoring other OS windows).
    bool                KeyCtrl;                            // Keyboard modifier down: Control
    bool                KeyShift;                           // Keyboard modifier down: Shift
    bool                KeyAlt;                             // Keyboard modifier down: Alt
    bool                KeySuper;                           // Keyboard modifier down: Cmd/Super/Windows

    // Other state maintained from data above + IO function calls
    SwGuiKeyChord       KeyMods;                          // Key mods flags (any of SwGuiMod_Ctrl/SwGuiMod_Shift/SwGuiMod_Alt/SwGuiMod_Super flags, same as io.KeyCtrl/KeyShift/KeyAlt/KeySuper but merged into flags. DOES NOT CONTAINS SwGuiMod_Shortcut which is pretranslated). Read-only, updated by NewFrame()
    SwGuiKeyData        KeysData[SwGuiKey_KeysData_SIZE]; // Key state for all known keys. Use IsKeyXXX() functions to access this.
    bool                WantCaptureMouseUnlessPopupClose;   // Alternative to WantCaptureMouse: (WantCaptureMouse == true && WantCaptureMouseUnlessPopupClose == false) when a click over void is expected to close a popup.
    SwVec2              MousePosPrev;                       // Previous mouse position (note that MouseDelta is not necessary == MousePos-MousePosPrev, in case either position is invalid)
    SwVec2              MouseClickedPos[5];                 // Position at time of clicking
    double              MouseClickedTime[5];                // Time of last click (used to figure out double-click)
    bool                MouseClicked[5];                    // Mouse button went from !Down to Down (same as MouseClickedCount[x] != 0)
    bool                MouseDoubleClicked[5];              // Has mouse button been double-clicked? (same as MouseClickedCount[x] == 2)
    SwU16               MouseClickedCount[5];               // == 0 (not clicked), == 1 (same as MouseClicked[]), == 2 (double-clicked), == 3 (triple-clicked) etc. when going from !Down to Down
    SwU16               MouseClickedLastCount[5];           // Count successive number of clicks. Stays valid after mouse release. Reset after another click is done.
    bool                MouseReleased[5];                   // Mouse button went from Down to !Down
    bool                MouseDownOwned[5];                  // Track if button was clicked inside a  imgui window or over void blocked by a popup. We don't request mouse capture from the application if click started outside SwGui bounds.
    bool                MouseDownOwnedUnlessPopupClose[5];  // Track if button was clicked inside a  imgui window.
    bool                MouseWheelRequestAxisSwap;          // On a non-Mac system, holding SHIFT requests WheelY to perform the equivalent of a WheelX event. On a Mac system this is already enforced by the system.
    float               MouseDownDuration[5];               // Duration the mouse button has been down (0.0f == just clicked)
    float               MouseDownDurationPrev[5];           // Previous time the mouse button has been down
    SwVec2              MouseDragMaxDistanceAbs[5];         // Maximum distance, absolute, on each axis, of how much mouse has traveled from the clicking point
    float               MouseDragMaxDistanceSqr[5];         // Squared maximum distance of how much mouse has traveled from the clicking point (used for moving thresholds)
    float               PenPressure;                        // Touch/Pen pressure (0.0f to 1.0f, should be >0.0f only when MouseDown[0] == true). Helper storage currently unused by  SwGui.
    bool                AppFocusLost;                       // Only modify via AddFocusEvent()
    bool                AppAcceptingEvents;                 // Only modify via SetAppAcceptingEvents()
    SwS8                BackendUsingLegacyKeyArrays;        // -1: unknown, 0: using AddKeyEvent(), 1: using legacy io.KeysDown[]
    bool                BackendUsingLegacyNavInputArray;    // 0: using AddKeyAnalogEvent(), 1: writing to legacy io.NavInputs[] directly
    SwWchar16           InputQueueSurrogate;                // For AddInputCharacterUTF16()
    SwVector<SwWchar>   InputQueueCharacters;         // Queue of _characters_ input (obtained by platform backend). Fill using AddInputCharacter() helper.

    SW_API   SwGuiIO();
};

//-----------------------------------------------------------------------------
// [SECTION] Helpers (SwGuiOnceUponAFrame, SwGuiTextFilter, SwGuiTextBuffer, SwGuiStorage, SwGuiListClipper, SwColor)
//-----------------------------------------------------------------------------

// Helper: Unicode defines
#define SW_UNICODE_CODEPOINT_INVALID 0xFFFD     // Invalid Unicode code point (standard value).
#ifdef SW_USE_WCHAR32
#define SW_UNICODE_CODEPOINT_MAX     0x10FFFF   // Maximum Unicode code point supported by this build.
#else
#define SW_UNICODE_CODEPOINT_MAX     0xFFFF     // Maximum Unicode code point supported by this build.
#endif

// Helper: Execute a block of code at maximum once a frame. Convenient if you want to quickly create a UI within deep-nested code that runs multiple times every frame.
// Usage: static SwGuiOnceUponAFrame oaf; if (oaf) SW::Text("This will be called only once per frame");
struct SwGuiOnceUponAFrame
{
    SwGuiOnceUponAFrame() { RefFrame = -1; }
    mutable int RefFrame;
    operator bool() const { int current_frame = SW::GetFrameCount(); if (RefFrame == current_frame) return false; RefFrame = current_frame; return true; }
};

// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
struct SwGuiTextFilter
{
    SW_API              SwGuiTextFilter(const char* default_filter = "");
    SW_API bool         Draw(const char* label = "Filter (inc,-exc)", float width = 0.0f);  // Helper calling InputText+Build
    SW_API bool         PassFilter(const char* text, const char* text_end = NULL) const;
    SW_API void         Build();
    void                Clear() { InputBuf[0] = 0; Build(); }
    bool                IsActive() const { return !Filters.empty(); }

    // [Internal]
    struct SwGuiTextRange
    {
        const char* b;
        const char* e;

        SwGuiTextRange() { b = e = NULL; }
        SwGuiTextRange(const char* _b, const char* _e) { b = _b; e = _e; }
        bool            empty() const { return b == e; }
        SW_API void     split(char separator, SwVector<SwGuiTextRange>* out) const;
    };
    char                            InputBuf[256];
    SwVector<SwGuiTextRange>    Filters;
    int                             CountGrep;
};

// Helper: Growable text buffer for logging/accumulating text
// (this could be called 'SwGuiTextBuilder' / 'SwGuiStringBuilder')
struct SwGuiTextBuffer
{
    SwVector<char>      Buf;
    SW_API static char  EmptyString[1];

    SwGuiTextBuffer() { }
    inline char         operator[](int i) const { SW_ASSERT(Buf.Data != NULL); return Buf.Data[i]; }
    const char*         begin() const { return Buf.Data ? &Buf.front() : EmptyString; }
    const char*         end() const { return Buf.Data ? &Buf.back() : EmptyString; }   // Buf is zero-terminated, so end() will point on the zero-terminator
    int                 size() const { return Buf.Size ? Buf.Size - 1 : 0; }
    bool                empty() const { return Buf.Size <= 1; }
    void                clear() { Buf.clear(); }
    void                reserve(int capacity) { Buf.reserve(capacity); }
    const char*         c_str() const { return Buf.Data ? Buf.Data : EmptyString; }
    SW_API void         append(const char* str, const char* str_end = NULL);
    SW_API void         appendf(const char* fmt, ...) SW_FMTARGS(2);
    SW_API void         appendfv(const char* fmt, va_list args) SW_FMTLIST(2);
};

// Helpers macros to generate 32-bit encoded colors
// User can declare their own format by #defining the 5 _SHIFT/_MASK macros in their imconfig file.
#ifndef SW_COL32_R_SHIFT
#ifdef SW_USE_BGRA_PACKED_COLOR
#define SW_COL32_R_SHIFT    16
#define SW_COL32_G_SHIFT    8
#define SW_COL32_B_SHIFT    0
#define SW_COL32_A_SHIFT    24
#define SW_COL32_A_MASK     0xFF000000
#else
#define SW_COL32_R_SHIFT    0
#define SW_COL32_G_SHIFT    8
#define SW_COL32_B_SHIFT    16
#define SW_COL32_A_SHIFT    24
#define SW_COL32_A_MASK     0xFF000000
#endif
#endif
#define SW_COL32(R,G,B,A)    (((SwU32)(A)<<SW_COL32_A_SHIFT) | ((SwU32)(B)<<SW_COL32_B_SHIFT) | ((SwU32)(G)<<SW_COL32_G_SHIFT) | ((SwU32)(R)<<SW_COL32_R_SHIFT))
#define SW_COL32_WHITE       SW_COL32(255,255,255,255)  // Opaque white = 0xFFFFFFFF
#define SW_COL32_BLACK       SW_COL32(0,0,0,255)        // Opaque black
#define SW_COL32_BLACK_TRANS SW_COL32(0,0,0,0)          // Transparent black = 0x00000000

// Helper: ImColor() implicitly converts colors to either SwU32 (packed 4x1 byte) or SwVec4 (4x1 float)
// Prefer using SW_COL32() macros if you want a guaranteed compile-time SwU32 for usage with SwDrawList API.
// **Avoid storing ImColor! Store either u32 of SwVec4. This is not a full-featured color class. MAY OBSOLETE.
// **None of the SwGui API are using ImColor directly but you can use it as a convenience to pass colors in either SwU32 or SwVec4 formats. Explicitly cast to SwU32 or SwVec4 if needed.
struct SwColor
{
    SwVec4            Value;

    constexpr SwColor() { }
    constexpr SwColor(float r, float g, float b, float a = 1.0f) : Value(r, g, b, a) { }
    constexpr SwColor(const SwVec4& col) : Value(col) {}
    SwColor(int r, int g, int b, int a = 255) { float sc = 1.0f / 255.0f; Value.x = (float)r * sc; Value.y = (float)g * sc; Value.z = (float)b * sc; Value.w = (float)a * sc; }
    SwColor(SwU32 rgba) { float sc = 1.0f / 255.0f; Value.x = (float)((rgba >> SW_COL32_R_SHIFT) & 0xFF) * sc; Value.y = (float)((rgba >> SW_COL32_G_SHIFT) & 0xFF) * sc; Value.z = (float)((rgba >> SW_COL32_B_SHIFT) & 0xFF) * sc; Value.w = (float)((rgba >> SW_COL32_A_SHIFT) & 0xFF) * sc; }
    inline operator SwU32() const { return SW::ColorConvertFloat4ToU32(Value); }
    inline operator SwVec4() const { return Value; }

    // FIXME-OBSOLETE: May need to obsolete/cleanup those helpers.
    inline void         SetHSV(float h, float s, float v, float a = 1.0f) { SW::ColorConvertHSVtoRGB(h, s, v, Value.x, Value.y, Value.z); Value.w = a; }
    static SwColor      HSV(float h, float s, float v, float a = 1.0f) { float r, g, b; SW::ColorConvertHSVtoRGB(h, s, v, r, g, b); return SwColor(r, g, b, a); }
};

struct SwTexture
{
    SwTextureID     textureId = NULL;
    const char*     imagePath = NULL;
    int             imageWidth = 0;
    int             imageHeight = 0;
    int             channel = 0;
};

// Helper: Key->Value storage
// Typically you don't have to worry about this since a storage is held within each Window.
// We use it to e.g. store collapse state for a tree (Int 0/1)
// This is optimized for efficient lookup (dichotomy into a contiguous buffer) and rare insertion (typically tied to user interactions aka max once a frame)
// You can use it as custom user storage for temporary values. Declare your own storage if, for example:
// - You want to manipulate the open/close state of a particular sub-tree in your interface (tree node uses Int 0/1 to store their state).
// - You want to store custom debug data easily without adding or editing structures in your code (probably not efficient, but convenient)
// Types are NOT stored, so it is up to you to make sure your Key don't collide with different types.
struct SwGuiStorage
{
    // [Internal]
    struct SwGuiStoragePair
    {
        SwGuiID key;
        union { int val_i; float val_f; void* val_p; };
        SwGuiStoragePair(SwGuiID _key, int _val_i) { key = _key; val_i = _val_i; }
        SwGuiStoragePair(SwGuiID _key, float _val_f) { key = _key; val_f = _val_f; }
        SwGuiStoragePair(SwGuiID _key, void* _val_p) { key = _key; val_p = _val_p; }
    };

    SwVector<SwGuiStoragePair>      Data;

    // - Get***() functions find pair, never add/allocate. Pairs are sorted so a query is O(log N)
    // - Set***() functions find pair, insertion on demand if missing.
    // - Sorted insertion is costly, paid once. A typical frame shouldn't need to insert any new pair.
    void                Clear() { Data.clear(); }
    SW_API int          GetInt(SwGuiID key, int default_val = 0) const;
    SW_API void         SetInt(SwGuiID key, int val);
    SW_API bool         GetBool(SwGuiID key, bool default_val = false) const;
    SW_API void         SetBool(SwGuiID key, bool val);
    SW_API float        GetFloat(SwGuiID key, float default_val = 0.0f) const;
    SW_API void         SetFloat(SwGuiID key, float val);
    SW_API void*        GetVoidPtr(SwGuiID key) const; // default_val is NULL
    SW_API void         SetVoidPtr(SwGuiID key, void* val);

    // - Get***Ref() functions finds pair, insert on demand if missing, return pointer. Useful if you intend to do Get+Set.
    // - References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.
    // - A typical use case where this is convenient for quick hacking (e.g. add storage during a live Edit&Continue session if you can't modify existing struct)
    //      float* pvar = SW::GetFloatRef(key); SW::SliderFloat("var", pvar, 0, 100.0f); some_var += *pvar;
    SW_API int*         GetIntRef(SwGuiID key, int default_val = 0);
    SW_API bool*        GetBoolRef(SwGuiID key, bool default_val = false);
    SW_API float*       GetFloatRef(SwGuiID key, float default_val = 0.0f);
    SW_API void**       GetVoidPtrRef(SwGuiID key, void* default_val = NULL);

    // Use on your own storage if you know only integer are being stored (open/close all tree nodes)
    SW_API void         SetAllInt(int val);

    // For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
    SW_API void         BuildSortByKey();
};

//-----------------------------------------------------------------------------
// [SECTION] Drawing API (SwDrawCmd, SwDrawIdx, SwDrawVert, SwDrawChannel, SwDrawListSplitter, SwDrawListFlags, SwDrawList, SwDrawData)
// Hold a series of drawing commands. The user provides a renderer for SwDrawData which essentially contains an array of SwDrawList.
//-----------------------------------------------------------------------------

// The maximum line width to bake anti-aliased textures for. Build atlas with SwFontAtlasFlags_NoBakedLines to disable baking.
#ifndef SW_DRAWLIST_TEX_LINES_WIDTH_MAX
#define SW_DRAWLIST_TEX_LINES_WIDTH_MAX     (63)
#endif

// SwDrawCallback: Draw callbacks for advanced uses [configurable type: override in imconfig.h]
// NB: You most likely do NOT need to use draw callbacks just to create your own widget or customized UI rendering,
// you can poke into the draw list for that! Draw callback may be useful for example to:
//  A) Change your GPU render state,
//  B) render a complex 3D scene inside a UI element without an intermediate texture/render target, etc.
// The expected behavior from your rendering function is 'if (cmd.UserCallback != NULL) { cmd.UserCallback(parent_list, cmd); } else { RenderTriangles() }'
// If you want to override the signature of SwDrawCallback, you can simply use e.g. '#define SwDrawCallback MyDrawCallback' (in imconfig.h) + update rendering backend accordingly.
#ifndef SwDrawCallback
typedef void (*SwDrawCallback)(const SwDrawList* parent_list, const SwDrawCmd* cmd);
#endif

// Special Draw callback value to request renderer backend to reset the graphics/render state.
// The renderer backend needs to handle this special value, otherwise it will crash trying to call a function at this address.
// This is useful for example if you submitted callbacks which you know have altered the render state and you want it to be restored.
// It is not done by default because they are many perfectly useful way of altering render state for imgui contents (e.g. changing shader/blending settings before an Swage call).
#define SwDrawCallback_ResetRenderState     (SwDrawCallback)(-1)

// Typically, 1 command = 1 GPU draw call (unless command is a callback)
// - VtxOffset: When 'io.BackendFlags & SwGuiBackendFlags_RendererHasVtxOffset' is enabled,
//   this fields allow us to render meshes larger than 64K vertices while keeping 16-bit indices.
//   Backends made for <1.71. will typically ignore the VtxOffset fields.
// - The ClipRect/TextureId/VtxOffset fields must be contiguous as we memcmp() them together (this is asserted for).
struct SwDrawCmd
{
    SwVec4              ClipRect;           // 4*4  // Clipping rectangle (x1, y1, x2, y2). Subtract SwDrawData->DisplayPos to get clipping rectangle in "viewport" coordinates
    SwTextureID         TextureId;          // 4-8  // User-provided texture ID. Set by user in SwfontAtlas::SetTexID() for fonts or passed to Swage*() functions. Ignore if never using images or multiple fonts atlas.
    unsigned int        VtxOffset;          // 4    // Start offset in vertex buffer. SwGuiBackendFlags_RendererHasVtxOffset: always 0, otherwise may be >0 to support meshes larger than 64K vertices with 16-bit indices.
    unsigned int        IdxOffset;          // 4    // Start offset in index buffer.
    unsigned int        ElemCount;          // 4    // Number of indices (multiple of 3) to be rendered as triangles. Vertices are stored in the callee SwDrawList's vtx_buffer[] array, indices in idx_buffer[].
    SwDrawCallback      UserCallback;       // 4-8  // If != NULL, call the function instead of rendering the vertices. clip_rect and texture_id will be set normally.
    void*               UserCallbackData;   // 4-8  // The draw callback code can access this.

    SwDrawCmd() { memset(this, 0, sizeof(*this)); } // Also ensure our padding fields are zeroed

    // Since 1.83: returns SwTextureID associated with this draw call. Warning: DO NOT assume this is always same as 'TextureId' (we will change this function for an upcoming feature)
    inline SwTextureID GetTexID() const { return TextureId; }
};

// Vertex layout
#ifndef SW_OVERRIDE_DRAWVERT_STRUCT_LAYOUT
struct SwDrawVert
{
    SwVec2  pos;
    SwVec2  uv;
    SwU32   col;
};
#else
// You can override the vertex format layout by defining SW_OVERRIDE_DRAWVERT_STRUCT_LAYOUT in imconfig.h
// The code expect SwVec2 pos (8 bytes), SwVec2 uv (8 bytes), SwU32 col (4 bytes), but you can re-order them or add other fields as needed to simplify integration in your engine.
// The type has to be described within the macro (you can either declare the struct or use a typedef). This is because SwVec2/SwU32 are likely not declared at the time you'd want to set your type up.
// NOTE: SWGUI DOESN'T CLEAR THE STRUCTURE AND DOESN'T CALL A CONSTRUCTOR SO ANY CUSTOM FIELD WILL BE UNINITIALIZED. IF YOU ADD EXTRA FIELDS (SUCH AS A 'Z' COORDINATES) YOU WILL NEED TO CLEAR THEM DURING RENDER OR TO IGNORE THEM.
SW_OVERRIDE_DRAWVERT_STRUCT_LAYOUT;
#endif

// [Internal] For use by SwDrawList
struct SwDrawCmdHeader
{
    SwVec4              ClipRect;
    SwTextureID         TextureId;
    unsigned int        VtxOffset;
};

// [Internal] For use by SwDrawListSplitter
struct SwDrawChannel
{
    SwVector<SwDrawCmd>         _CmdBuffer;
    SwVector<SwDrawIdx>         _IdxBuffer;
};


// Split/Merge functions are used to split the draw list into different layers which can be drawn into out of order.
// This is used by the Columns/Tables API, so items of each column can be batched together in a same draw call.
struct SwDrawListSplitter
{
    int                             _Current;    // Current channel number (0)
    int                             _Count;      // Number of active channels (1+)
    SwVector<SwDrawChannel>         _Channels;   // Draw channels (not resized down so _Count might be < Channels.Size)

    inline SwDrawListSplitter() { memset(this, 0, sizeof(*this)); }
    inline ~SwDrawListSplitter() { /*ClearFreeMemory();*/ }
    inline void                     Clear() { _Current = 0; _Count = 1; } // Do not clear Channels[] so our allocations are reused next frame
    SW_API void                     ClearFreeMemory();
    SW_API void                     Split(SwDrawList* draw_list, int count);
    SW_API void                     Merge(SwDrawList* draw_list);
    SW_API void                     SetCurrentChannel(SwDrawList* draw_list, int channel_idx);
};

// Flags for SwDrawList functions
// (Legacy: bit 0 must always correspond to SwDrawFlags_Closed to be backward compatible with old API using a bool. Bits 1..3 must be unused)
enum SwDrawFlags_
{
    SwDrawFlags_None = 0,
    SwDrawFlags_Closed = 1 << 0, // PathStroke(), AddPolyline(): specify that shape should be closed (Swportant: this is always == 1 for legacy reason)
    SwDrawFlags_RoundCornersTopLeft = 1 << 4, // AddRect(), AddRectFilled(), PathRect(): enable rounding top-left corner only (when rounding > 0.0f, we default to all corners). Was 0x01.
    SwDrawFlags_RoundCornersTopRight = 1 << 5, // AddRect(), AddRectFilled(), PathRect(): enable rounding top-right corner only (when rounding > 0.0f, we default to all corners). Was 0x02.
    SwDrawFlags_RoundCornersBottomLeft = 1 << 6, // AddRect(), AddRectFilled(), PathRect(): enable rounding bottom-left corner only (when rounding > 0.0f, we default to all corners). Was 0x04.
    SwDrawFlags_RoundCornersBottomRight = 1 << 7, // AddRect(), AddRectFilled(), PathRect(): enable rounding bottom-right corner only (when rounding > 0.0f, we default to all corners). Wax 0x08.
    SwDrawFlags_RoundCornersNone = 1 << 8, // AddRect(), AddRectFilled(), PathRect(): disable rounding on all corners (when rounding > 0.0f). This is NOT zero, NOT an implicit flag!
    SwDrawFlags_RoundCornersTop = SwDrawFlags_RoundCornersTopLeft | SwDrawFlags_RoundCornersTopRight,
    SwDrawFlags_RoundCornersBottom = SwDrawFlags_RoundCornersBottomLeft | SwDrawFlags_RoundCornersBottomRight,
    SwDrawFlags_RoundCornersLeft = SwDrawFlags_RoundCornersBottomLeft | SwDrawFlags_RoundCornersTopLeft,
    SwDrawFlags_RoundCornersRight = SwDrawFlags_RoundCornersBottomRight | SwDrawFlags_RoundCornersTopRight,
    SwDrawFlags_RoundCornersAll = SwDrawFlags_RoundCornersTopLeft | SwDrawFlags_RoundCornersTopRight | SwDrawFlags_RoundCornersBottomLeft | SwDrawFlags_RoundCornersBottomRight,
    SwDrawFlags_RoundCornersDefault_ = SwDrawFlags_RoundCornersAll, // Default to ALL corners if none of the _RoundCornersXX flags are specified.
    SwDrawFlags_RoundCornersMask_ = SwDrawFlags_RoundCornersAll | SwDrawFlags_RoundCornersNone,
};

// Flags for SwDrawList instance. Those are set automatically by SW:: functions from SwGuiIO settings, and generally not manipulated directly.
// It is however possible to temporarily alter flags between calls to SwDrawList:: functions.
enum SwDrawListFlags_
{
    SwDrawListFlags_None = 0,
    SwDrawListFlags_AntiAliasedLines = 1 << 0,  // Enable anti-aliased lines/borders (*2 the number of triangles for 1.0f wide line or lines thin enough to be drawn using textures, otherwise *3 the number of triangles)
    SwDrawListFlags_AntiAliasedLinesUseTex = 1 << 1,  // Enable anti-aliased lines/borders using textures when possible. Require backend to render with bilinear filtering (NOT point/nearest filtering).
    SwDrawListFlags_AntiAliasedFill = 1 << 2,  // Enable anti-aliased edge around filled shapes (rounded rectangles, circles).
    SwDrawListFlags_AllowVtxOffset = 1 << 3,  // Can emit 'VtxOffset > 0' to allow large meshes. Set when 'SwGuiBackendFlags_RendererHasVtxOffset' is enabled.
};

// Draw command list
// This is the low-level list of polygons that SW:: functions are filling. At the end of the frame,
// all command lists are passed to your SwGuiIO::RenderDrawListFn function for rendering.
// Each  imgui window contains its own SwDrawList. You can use SW::GetWindowDrawList() to
// access the current window draw list and draw custom primitives.
// You can interleave normal SW:: calls and adding primitives to the current draw list.
// In single viewport mode, top-left is == GetMainViewport()->Pos (generally 0,0), bottom-right is == GetMainViewport()->Pos+Size (generally io.DisplaySize).
// You are totally free to apply whatever transformation matrix to want to the data (depending on the use of the transformation you may want to apply it to ClipRect as well!)
// Important: Primitives are always added to the list and not culled (culling is done at higher-level by SW:: functions), if you use this API a lot consider coarse culling your drawn objects.
struct SwDrawList
{
    // This is what you have to render
    SwVector<SwDrawCmd>         CmdBuffer;          // Draw commands. Typically 1 command = 1 GPU draw call, unless the command is a callback.
    SwVector<SwDrawIdx>         IdxBuffer;          // Index buffer. Each command consume SwDrawCmd::ElemCount of those
    SwVector<SwDrawVert>        VtxBuffer;          // Vertex buffer.
    SwDrawListFlags             Flags;              // Flags, you may poke into these to adjust anti-aliasing settings per-primitive.

    // [Internal, used while building lists]
    unsigned int                _VtxCurrentIdx;     // [Internal] generally == VtxBuffer.Size unless we are past 64K vertices, in which case this gets reset to 0.
    const SwDrawListSharedData* _Data;          // Pointer to shared draw data (you can use SW::GetDrawListSharedData() to get the one from current SwGui context)
    const char*                 _OwnerName;         // Pointer to owner window's name for debugging
    SwDrawVert*                 _VtxWritePtr;       // [Internal] point within VtxBuffer.Data after each add command (to avoid using the SwVector<> operators too much)
    SwDrawIdx*                  _IdxWritePtr;       // [Internal] point within IdxBuffer.Data after each add command (to avoid using the SwVector<> operators too much)
    SwVector<SwVec4>            _ClipRectStack;     // [Internal]
    SwVector<SwTextureID>       _TextureIdStack;    // [Internal]
    SwVector<SwVec2>            _Path;              // [Internal] current path building
    SwDrawCmdHeader             _CmdHeader;         // [Internal] template of active commands. Fields should match those of CmdBuffer.back().
    SwDrawListSplitter          _Splitter;          // [Internal] for channels api (note: prefer using your own persistent instance of SwDrawListSplitter!)
    float                       _FringeScale;       // [Internal] anti-alias fringe is scaled by this value, this helps to keep things sharp while zooming at vertex buffer content

    // If you want to create SwDrawList instances, pass them SW::GetDrawListSharedData() or create and use your own SwDrawListSharedData (so you can use SwDrawList without SwGui)
    SwDrawList(const SwDrawListSharedData* shared_data) { memset(this, 0, sizeof(*this)); _Data = shared_data; }

    ~SwDrawList() { _ClearFreeMemory(); }
    SW_API void               PushClipRect(const SwVec2& clip_rect_min, const SwVec2& clip_rect_max, bool intersect_with_current_clip_rect = false);  // Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level SW::PushClipRect() to affect logic (hit-testing and widget culling)
    SW_API void               PushClipRectFullScreen();
    SW_API void               PopClipRect();
    SW_API void               PushTextureID(SwTextureID texture_id);
    SW_API void               PopTextureID();
    inline SwVec2             GetClipRectMin() const { const SwVec4& cr = _ClipRectStack.back(); return SwVec2(cr.x, cr.y); }
    inline SwVec2             GetClipRectMax() const { const SwVec4& cr = _ClipRectStack.back(); return SwVec2(cr.z, cr.w); }

    // Primitives
    // - Filled shapes must always use clockwise winding order. The anti-aliasing fringe depends on it. Counter-clockwise shapes will have "inward" anti-aliasing.
    // - For rectangular primitives, "p_min" and "p_max" represent the upper-left and lower-right corners.
    // - For circle primitives, use "num_segments == 0" to automatically calculate tessellation (preferred).
    //   In older versions (until  SwGui 1.77) the AddCircle functions defaulted to num_segments == 12.
    //   In future versions we will use textures to provide cheaper and higher-quality circles.
    //   Use AddNgon() and AddNgonFilled() functions if you need to guarantee a specific number of sides.
    SW_API void  AddLine(const SwVec2& p1, const SwVec2& p2, SwU32 col, float thickness = 1.0f);
    SW_API void  AddRect(const SwVec2& p_min, const SwVec2& p_max, SwU32 col, float rounding = 0.0f, SwDrawFlags flags = 0, float thickness = 1.0f);   // a: upper-left, b: lower-right (== upper-left + size)
    SW_API void  AddRectFilled(const SwVec2& p_min, const SwVec2& p_max, SwU32 col, float rounding = 0.0f, SwDrawFlags flags = 0);                     // a: upper-left, b: lower-right (== upper-left + size)
    SW_API void  AddRectFilledMultiColor(const SwVec2& p_min, const SwVec2& p_max, SwU32 col_upr_left, SwU32 col_upr_right, SwU32 col_bot_right, SwU32 col_bot_left);
    SW_API void  AddQuad(const SwVec2& p1, const SwVec2& p2, const SwVec2& p3, const SwVec2& p4, SwU32 col, float thickness = 1.0f);
    SW_API void  AddQuadFilled(const SwVec2& p1, const SwVec2& p2, const SwVec2& p3, const SwVec2& p4, SwU32 col);
    SW_API void  AddTriangle(const SwVec2& p1, const SwVec2& p2, const SwVec2& p3, SwU32 col, float thickness = 1.0f);
    SW_API void  AddTriangleFilled(const SwVec2& p1, const SwVec2& p2, const SwVec2& p3, SwU32 col);
    SW_API void  AddCircle(const SwVec2& center, float radius, SwU32 col, int num_segments = 0, float thickness = 1.0f);
    SW_API void  AddCircleFilled(const SwVec2& center, float radius, SwU32 col, int num_segments = 0);
    SW_API void  AddNgon(const SwVec2& center, float radius, SwU32 col, int num_segments, float thickness = 1.0f);
    SW_API void  AddNgonFilled(const SwVec2& center, float radius, SwU32 col, int num_segments);
    SW_API void  AddText(const SwVec2& pos, SwU32 col, const char* text_begin, const char* text_end = NULL);
    SW_API void  AddText(const SwFont* font, float font_size, const SwVec2& pos, SwU32 col, const char* text_begin, const char* text_end = NULL, float wrap_width = 0.0f, const SwVec4* cpu_fine_clip_rect = NULL);
    SW_API void  AddPolyline(const SwVec2* points, int num_points, SwU32 col, SwDrawFlags flags, float thickness);
    SW_API void  AddConvexPolyFilled(const SwVec2* points, int num_points, SwU32 col);
    SW_API void  AddBezierCubic(const SwVec2& p1, const SwVec2& p2, const SwVec2& p3, const SwVec2& p4, SwU32 col, float thickness, int num_segments = 0); // Cubic Bezier (4 control points)
    SW_API void  AddBezierQuadratic(const SwVec2& p1, const SwVec2& p2, const SwVec2& p3, SwU32 col, float thickness, int num_segments = 0);               // Quadratic Bezier (3 control points)

    // 3D Primitives
    SW_API void  AddSphere(const char* name, const float size, const SwVec2& pos, SwVec4& axes, const int tessFactor);
    SW_API void  AddCube(const char* name, const float size, const SwVec2& pos, SwVec4& axes);
    SW_API void  AddCone(const char* name, const float length, const float radius, const int slices, const float size, const SwVec2& pos, SwVec4& axes);

    // Image primitives
    // - Read FAQ to understand what SwTextureID is.
    // - "p_min" and "p_max" represent the upper-left and lower-right corners of the rectangle.
    // - "uv_min" and "uv_max" represent the normalized texture coordinates to use for those corners. Using (0,0)->(1,1) texture coordinates will generally display the entire texture.
    SW_API void  AddImage(SwTextureID user_texture_id, const SwVec2& p_min, const SwVec2& p_max, const SwVec2& uv_min = SwVec2(0, 0), const SwVec2& uv_max = SwVec2(1, 1), SwU32 col = SW_COL32_WHITE);
    SW_API void  AddImageQuad(SwTextureID user_texture_id, const SwVec2& p1, const SwVec2& p2, const SwVec2& p3, const SwVec2& p4, const SwVec2& uv1 = SwVec2(0, 0), const SwVec2& uv2 = SwVec2(1, 0), const SwVec2& uv3 = SwVec2(1, 1), const SwVec2& uv4 = SwVec2(0, 1), SwU32 col = SW_COL32_WHITE);
    SW_API void  AddImageRounded(SwTextureID user_texture_id, const SwVec2& p_min, const SwVec2& p_max, const SwVec2& uv_min, const SwVec2& uv_max, SwU32 col, float rounding, SwDrawFlags flags = 0);

    // Stateful path API, add points then finish with PathFillConvex() or PathStroke()
    // - Filled shapes must always use clockwise winding order. The anti-aliasing fringe depends on it. Counter-clockwise shapes will have "inward" anti-aliasing.
    inline void  PathClear() { _Path.Size = 0; }
    inline void  PathLineTo(const SwVec2& pos) { _Path.push_back(pos); }
    inline void  PathLineToMergeDuplicate(const SwVec2& pos) { if (_Path.Size == 0 || memcmp(&_Path.Data[_Path.Size - 1], &pos, 8) != 0) _Path.push_back(pos); }
    inline void  PathFillConvex(SwU32 col) { AddConvexPolyFilled(_Path.Data, _Path.Size, col); _Path.Size = 0; }
    inline void  PathStroke(SwU32 col, SwDrawFlags flags = 0, float thickness = 1.0f) { AddPolyline(_Path.Data, _Path.Size, col, flags, thickness); _Path.Size = 0; }
    SW_API void  PathArcTo(const SwVec2& center, float radius, float a_min, float a_max, int num_segments = 0);
    SW_API void  PathArcToFast(const SwVec2& center, float radius, int a_min_of_12, int a_max_of_12);                // Use precomputed angles for a 12 steps circle
    SW_API void  PathBezierCubicCurveTo(const SwVec2& p2, const SwVec2& p3, const SwVec2& p4, int num_segments = 0); // Cubic Bezier (4 control points)
    SW_API void  PathBezierQuadraticCurveTo(const SwVec2& p2, const SwVec2& p3, int num_segments = 0);               // Quadratic Bezier (3 control points)
    SW_API void  PathRect(const SwVec2& rect_min, const SwVec2& rect_max, float rounding = 0.0f, SwDrawFlags flags = 0);

    // Advanced
    SW_API void  AddCallback(SwDrawCallback callback, void* callback_data);  // Your rendering function must check for 'UserCallback' in SwDrawCmd and call the function instead of rendering triangles.
    SW_API void  AddDrawCmd();                                               // This is useful if you need to forcefully create a new draw call (to allow for dependent rendering / blending). Otherwise primitives are merged into the same draw-call as much as possible
    SW_API SwDrawList* CloneOutput() const;                                  // Create a clone of the CmdBuffer/IdxBuffer/VtxBuffer.

    // Advanced: Channels
    // - Use to split render into layers. By switching channels to can render out-of-order (e.g. submit FG primitives before BG primitives)
    // - Use to minimize draw calls (e.g. if going back-and-forth between multiple clipping rectangles, prefer to append into separate channels then merge at the end)
    // - FIXME-OBSOLETE: This API shouldn't have been in SwDrawList in the first place!
    //   Prefer using your own persistent instance of SwDrawListSplitter as you can stack them.
    //   Using the SwDrawList::ChannelsXXXX you cannot stack a split over another.
    inline void   ChannelsSplit(int count) { _Splitter.Split(this, count); }
    inline void   ChannelsMerge() { _Splitter.Merge(this); }
    inline void   ChannelsSetCurrent(int n) { _Splitter.SetCurrentChannel(this, n); }

    // Advanced: Primitives allocations
    // - We render triangles (three vertices)
    // - All primitives needs to be reserved via PrimReserve() beforehand.
    SW_API void   PrimReserve(int idx_count, int vtx_count);
    SW_API void   PrimUnreserve(int idx_count, int vtx_count);
    SW_API void   PrimRect(const SwVec2& a, const SwVec2& b, SwU32 col);      // Axis aligned rectangle (composed of two triangles)
    SW_API void   PrimRectUV(const SwVec2& a, const SwVec2& b, const SwVec2& uv_a, const SwVec2& uv_b, SwU32 col);
    SW_API void   PrimQuadUV(const SwVec2& a, const SwVec2& b, const SwVec2& c, const SwVec2& d, const SwVec2& uv_a, const SwVec2& uv_b, const SwVec2& uv_c, const SwVec2& uv_d, SwU32 col);
    inline void   PrimWriteVtx(const SwVec2& pos, const SwVec2& uv, SwU32 col) { _VtxWritePtr->pos = pos; _VtxWritePtr->uv = uv; _VtxWritePtr->col = col; _VtxWritePtr++; _VtxCurrentIdx++; }
    inline void   PrimWriteIdx(SwDrawIdx idx) { *_IdxWritePtr = idx; _IdxWritePtr++; }
    inline void   PrimVtx(const SwVec2& pos, const SwVec2& uv, SwU32 col) { PrimWriteIdx((SwDrawIdx)_VtxCurrentIdx); PrimWriteVtx(pos, uv, col); } // Write vertex with unique index

#ifndef SW_DISABLE_OBSOLETE_FUNCTIONS
    inline    void  AddBezierCurve(const SwVec2& p1, const SwVec2& p2, const SwVec2& p3, const SwVec2& p4, SwU32 col, float thickness, int num_segments = 0) { AddBezierCubic(p1, p2, p3, p4, col, thickness, num_segments); } // OBSOLETED in 1.80 (Jan 2021)
    inline    void  PathBezierCurveTo(const SwVec2& p2, const SwVec2& p3, const SwVec2& p4, int num_segments = 0) { PathBezierCubicCurveTo(p2, p3, p4, num_segments); } // OBSOLETED in 1.80 (Jan 2021)
#endif

    // [Internal helpers]
    SW_API void  _ResetForNewFrame();
    SW_API void  _ClearFreeMemory();
    SW_API void  _PopUnusedDrawCmd();
    SW_API void  _TryMergeDrawCmds();
    SW_API void  _OnChangedClipRect();
    SW_API void  _OnChangedTextureID();
    SW_API void  _OnChangedVtxOffset();
    SW_API int   _CalcCircleAutoSegmentCount(float radius) const;
    SW_API void  _PathArcToFastEx(const SwVec2& center, float radius, int a_min_sample, int a_max_sample, int a_step);
    SW_API void  _PathArcToN(const SwVec2& center, float radius, float a_min, float a_max, int num_segments);
};

// All draw data to render a  SwGui frame
// (NB: the style and the naming convention here is a little inconsistent, we currently preserve them for backward compatibility purpose,
// as this is one of the oldest structure exposed by the library! Basically, SwDrawList == CmdList)
struct SwDrawData
{
    bool              Valid;                  // Only valid after Render() is called and before the next NewFrame() is called.
    int               CmdListsCount;          // Number of SwDrawList* to render
    int               TotalIdxCount;          // For convenience, sum of all SwDrawList's IdxBuffer.Size
    int               TotalVtxCount;          // For convenience, sum of all SwDrawList's VtxBuffer.Size
    SwVector<SwDrawList*> CmdLists;         // Array of SwDrawList* to render. The SwDrawLists are owned by SwGuiContext and only pointed to from here.
    SwVec2          DisplayPos;             // Top-left position of the viewport to render (== top-left of the orthogonal projection matrix to use) (== GetMainViewport()->Pos for the main viewport, == (0.0) in most single-viewport applications)
    SwVec2          DisplaySize;            // Size of the viewport to render (== GetMainViewport()->Size for the main viewport, == io.DisplaySize in most single-viewport applications)
    SwVec2          FramebufferScale;       // Amount of pixels for each unit of DisplaySize. Based on io.DisplayFramebufferScale. Generally (1,1) on normal display, (2,2) on OSX with Retina display.
    SwGuiViewport*  OwnerViewport;          // Viewport carrying the SwDrawData instance, might be of use to the renderer (generally not).

    // Functions
    SwDrawData() { Clear(); }
    SW_API void  Clear();
    SW_API void  AddDrawList(SwDrawList* draw_list);     // Helper to add an external draw list into an existing SwDrawData.
    SW_API void  DeIndexAllBuffers();                    // Helper to convert all buffers from indexed to non-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering!
    SW_API void  ScaleClipRects(const SwVec2& fb_scale); // Helper to scale the ClipRect field of each SwDrawCmd. Use if your final output buffer is at a different scale than  SwGui expects, or if there is a difference between your window resolution and framebuffer resolution.
};

//-----------------------------------------------------------------------------
// [SECTION] Font API (SwFontConfig, SwFontGlyph, SwFontAtlasFlags, SwFontAtlas, SwFontGlyphRangesBuilder, SwFont)
//-----------------------------------------------------------------------------

struct SwFontConfig
{
    void*               FontData;               //          // TTF/OTF data
    int                 FontDataSize;           //          // TTF/OTF data size
    bool                FontDataOwnedByAtlas;   // true     // TTF/OTF data ownership taken by the container SwFontAtlas (will delete memory itself).
    int                 FontNo;                 // 0        // Index of font within TTF/OTF file
    float               SizePixels;             //          // Size in pixels for rasterizer (more or less maps to the resulting font height).
    int                 OversampleH;            // 3        // Rasterize at higher quality for sub-pixel positioning. Note the difference between 2 and 3 is minimal so you can reduce this to 2 to save memory. Read https://github.com/nothings/stb/blob/master/tests/oversample/README.md for details.
    int                 OversampleV;            // 1        // Rasterize at higher quality for sub-pixel positioning. This is not really useful as we don't use sub-pixel positions on the Y axis.
    bool                PixelSnapH;             // false    // Align every glyph to pixel boundary. Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, you can set OversampleH/V to 1.
    SwVec2              GlyphExtraSpacing;      // 0, 0     // Extra spacing (in pixels) between glyphs. Only X axis is supported for now.
    SwVec2              GlyphOffset;            // 0, 0     // Offset all glyphs from this font input.
    const SwWchar*      GlyphRanges;            // NULL     // Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE.
    float               GlyphMinAdvanceX;       // 0        // Swmum AdvanceX for glyphs, set Min to align font icons, set both Min/Max to enforce mono-space font
    float               GlyphMaxAdvanceX;       // FLT_MAX  // Maximum AdvanceX for glyphs
    bool                MergeMode;              // false    // Merge into previous SwFont, so you can combine multiple inputs font into one SwFont (e.g. ASCII font + icons + Japanese glyphs). You may want to use GlyphOffset.y when merge font of different heights.
    unsigned int        FontBuilderFlags;       // 0        // Settings for custom font builder. THIS IS BUILDER IMPLEMENTATION DEPENDENT. Leave as zero if unsure.
    float               RasterizerMultiply;     // 1.0f     // Brighten (>1.0f) or darken (<1.0f) font output. Brightening small fonts may be a good workaround to make them more readable.
    SwWchar             EllipsisChar;           // -1       // Explicitly specify unicode codepoint of ellipsis character. When fonts are being merged first specified ellipsis will be used.

    // [Internal]
    char                Name[40];               // Name (strictly to ease debugging)
    SwFont*             DstFont;

    SW_API SwFontConfig();
};

// Hold rendering data for one glyph.
// (Note: some language parsers may fail to convert the 31+1 bitfield members, in this case maybe drop store a single u32 or we can rework this)
struct SwFontGlyph
{
    unsigned int    Colored : 1;        // Flag to indicate glyph is colored and should generally ignore tinting (make it usable with no shift on little-endian as this is used in loops)
    unsigned int    Visible : 1;        // Flag to indicate glyph has no visible pixels (e.g. space). Allow early out when rendering.
    unsigned int    Codepoint : 30;     // 0x0000..0x10FFFF
    float           AdvanceX;           // Distance to next character (= data from font + SwFontConfig::GlyphExtraSpacing.x baked in)
    float           X0, Y0, X1, Y1;     // Glyph corners
    float           U0, V0, U1, V1;     // Texture coordinates
};

// Helper to build glyph ranges from text/string data. Feed your application strings/characters to it then call BuildRanges().
// This is essentially a tightly packed of vector of 64k booleans = 8KB storage.
struct SwFontGlyphRangesBuilder
{
    SwVector<SwU32> UsedChars;            // Store 1-bit per Unicode code point (0=unused, 1=used)

    SwFontGlyphRangesBuilder() { Clear(); }
    inline void     Clear() { int size_in_bytes = (SW_UNICODE_CODEPOINT_MAX + 1) / 8; UsedChars.resize(size_in_bytes / (int)sizeof(SwU32)); memset(UsedChars.Data, 0, (size_t)size_in_bytes); }
    inline bool     GetBit(size_t n) const { int off = (int)(n >> 5); SwU32 mask = 1u << (n & 31); return (UsedChars[off] & mask) != 0; }  // Get bit n in the array
    inline void     SetBit(size_t n) { int off = (int)(n >> 5); SwU32 mask = 1u << (n & 31); UsedChars[off] |= mask; }               // Set bit n in the array
    inline void     AddChar(SwWchar c) { SetBit(c); }                      // Add character
    SW_API void     AddText(const char* text, const char* text_end = NULL);     // Add string (each character of the UTF-8 string are added)
    SW_API void     AddRanges(const SwWchar* ranges);                           // Add ranges, e.g. builder.AddRanges(SwFontAtlas::GetGlyphRangesDefault()) to force add all of ASCII/Latin+Ext
    SW_API void     BuildRanges(SwVector<SwWchar>* out_ranges);                 // Output new ranges
};

// See SwFontAtlas::AddCustomRectXXX functions.
struct SwFontAtlasCustomRect
{
    unsigned short      Width, Height;  // Input    // Desired rectangle dimension
    unsigned short      X, Y;           // Output   // Packed position in Atlas
    unsigned int        GlyphID;        // Input    // For custom font glyphs only (ID < 0x110000)
    float               GlyphAdvanceX;  // Input    // For custom font glyphs only: glyph xadvance
    SwVec2              GlyphOffset;    // Input    // For custom font glyphs only: glyph display offset
    SwFont*             Font;           // Input    // For custom font glyphs only: target font
    SwFontAtlasCustomRect() { Width = Height = 0; X = Y = 0xFFFF; GlyphID = 0; GlyphAdvanceX = 0.0f; GlyphOffset = SwVec2(0, 0); Font = NULL; }
    bool IsPacked() const { return X != 0xFFFF; }
};

// Flags for SwFontAtlas build
enum SwFontAtlasFlags_
{
    SwFontAtlasFlags_None = 0,
    SwFontAtlasFlags_NoPowerOfTwoHeight = 1 << 0,   // Don't round the height to next power of two
    SwFontAtlasFlags_NoMouseCursors = 1 << 1,   // Don't build software mouse cursors into the atlas (save a little texture memory)
    SwFontAtlasFlags_NoBakedLines = 1 << 2,   // Don't build thick line textures into the atlas (save a little texture memory, allow support for point/nearest filtering). The AntiAliasedLinesUseTex features uses them, otherwise they will be rendered using polygons (more expensive for CPU/GPU).
};

// Load and rasterize multiple TTF/OTF fonts into a same texture. The font atlas will build a single texture holding:
//  - One or more fonts.
//  - Custom graphics data needed to render the shapes needed by  SwGui.
//  - Mouse cursor shapes for software cursor rendering (unless setting 'Flags |= SwFontAtlasFlags_NoMouseCursors' in the font atlas).
// It is the user-code responsibility to setup/build the atlas, then upload the pixel data into a texture accessible by your graphics api.
//  - Optionally, call any of the AddFont*** functions. If you don't call any, the default font embedded in the code will be loaded for you.
//  - Call GetTexDataAsAlpha8() or GetTexDataAsRGBA32() to build and retrieve pixels data.
//  - Upload the pixels data into a texture within your graphics system (see mgui_impl_xxxx.cpp examples)
//  - Call SetTexID(my_tex_id); and pass the pointer/identifier to your texture in a format natural to your graphics API.
//    This value will be passed back to you during rendering to identify the texture. Read FAQ entry about SwTextureID for more details.
// Common pitfalls:
// - If you pass a 'glyph_ranges' array to AddFont*** functions, you need to make sure that your array persist up until the
//   atlas is build (when calling GetTexData*** or Build()). We only copy the pointer, not the data.
// - Important: By default, AddFontFromMemoryTTF() takes ownership of the data. Even though we are not writing to it, we will free the pointer on destruction.
//   You can set font_cfg->FontDataOwnedByAtlas=false to keep ownership of your data and it won't be freed,
// - Even though many functions are suffixed with "TTF", OTF data is supported just as well.
// - This is an old API and it is currently awkward for those and various other reasons! We will address them in the future!
struct SwFontAtlas
{
    SW_API SwFontAtlas();
    SW_API ~SwFontAtlas();
    SW_API SwFont*            AddFont(const SwFontConfig* font_cfg);
    SW_API SwFont*            AddFontDefault(const SwFontConfig* font_cfg = NULL);
    SW_API SwFont*            AddFontFromFileTTF(const char* filename, float size_pixels, const SwFontConfig* font_cfg = NULL, const SwWchar* glyph_ranges = NULL);
    SW_API SwFont*            AddFontFromMemoryTTF(void* font_data, int font_size, float size_pixels, const SwFontConfig* font_cfg = NULL, const SwWchar* glyph_ranges = NULL); // Note: Transfer ownership of 'ttf_data' to SwFontAtlas! Will be deleted after destruction of the atlas. Set font_cfg->FontDataOwnedByAtlas=false to keep ownership of your data and it won't be freed.
    SW_API SwFont*            AddFontFromMemoryCompressedTTF(const void* compressed_font_data, int compressed_font_size, float size_pixels, const SwFontConfig* font_cfg = NULL, const SwWchar* glyph_ranges = NULL); // 'compressed_font_data' still owned by caller. Compress with binary_to_compressed_c.cpp.
    SW_API SwFont*            AddFontFromMemoryCompressedBase85TTF(const char* compressed_font_data_base85, float size_pixels, const SwFontConfig* font_cfg = NULL, const SwWchar* glyph_ranges = NULL);              // 'compressed_font_data_base85' still owned by caller. Compress with binary_to_compressed_c.cpp with -base85 parameter.
    SW_API void               ClearInputData();           // Clear input data (all SwFontConfig structures including sizes, TTF data, glyph ranges, etc.) = all the data used to build the texture and fonts.
    SW_API void               ClearTexData();             // Clear output texture data (CPU side). Saves RAM once the texture has been copied to graphics memory.
    SW_API void               ClearFonts();               // Clear output font data (glyphs storage, UV coordinates).
    SW_API void               Clear();                    // Clear all input and output.

    // Build atlas, retrieve pixel data.
    // User is in charge of copying the pixels into graphics memory (e.g. create a texture with your engine). Then store your texture handle with SetTexID().
    // The pitch is always = Width * BytesPerPixels (1 or 4)
    // Building in RGBA32 format is provided for convenience and compatibility, but note that unless you manually manipulate or copy color data into
    // the texture (e.g. when using the AddCustomRect*** api), then the RGB pixels emitted will always be white (~75% of memory/bandwidth waste.
    SW_API bool                Build();                    // Build pixels data. This is called automatically for you by the GetTexData*** functions.
    SW_API void                GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL);  // 1 byte per-pixel
    SW_API void                GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL);  // 4 bytes-per-pixel
    bool                       IsBuilt() const { return Fonts.Size > 0 && TexReady; } // Bit ambiguous: used to detect when user didn't build texture but effectively we should check TexID != 0 except that would be backend dependent...
    void                       SetTexID(SwTextureID id) { TexID = id; }

    //-------------------------------------------
    // Glyph Ranges
    //-------------------------------------------

    // Helpers to retrieve list of common Unicode ranges (2 value per range, values are inclusive, zero-terminated list)
    // NB: Make sure that your string are UTF-8 and NOT in your local code page. In C++11, you can create UTF-8 string literal using the u8"Hello world" syntax. See FAQ for details.
    // NB: Consider using SwFontGlyphRangesBuilder to build glyph ranges from textual data.
    SW_API const SwWchar* GetGlyphRangesDefault();                // Basic Latin, Extended Latin
    SW_API const SwWchar* GetGlyphRangesKorean();                 // Default + Korean characters
    SW_API const SwWchar* GetGlyphRangesJapanese();               // Default + Hiragana, Katakana, Half-Width, Selection of 2999 Ideographs
    SW_API const SwWchar* GetGlyphRangesChineseFull();            // Default + Half-Width + Japanese Hiragana/Katakana + full set of about 21000 CJK Unified Ideographs
    SW_API const SwWchar* GetGlyphRangesChineseSimplifiedCommon();// Default + Half-Width + Japanese Hiragana/Katakana + set of 2500 CJK Unified Ideographs for common simplified Chinese
    SW_API const SwWchar* GetGlyphRangesCyrillic();               // Default + about 400 Cyrillic characters
    SW_API const SwWchar* GetGlyphRangesThai();                   // Default + Thai characters
    SW_API const SwWchar* GetGlyphRangesVietnamese();             // Default + Vietnamese characters

    //-------------------------------------------
    // [BETA] Custom Rectangles/Glyphs API
    //-------------------------------------------

    // You can request arbitrary rectangles to be packed into the atlas, for your own purposes.
    // - After calling Build(), you can query the rectangle position and render your pixels.
    // - If you render colored output, set 'atlas->TexPixelsUseColors = true' as this may help some backends decide of prefered texture format.
    // - You can also request your rectangles to be mapped as font glyph (given a font + Unicode point),
    //   so you can render e.g. custom colorful icons and use them as regular glyphs.
    // - Read docs/FONTS.md for more details about using colorful icons.
    // - Note: this API may be redesigned later in order to support multi-monitor varying DPI settings.
    SW_API int               AddCustomRectRegular(int width, int height);
    SW_API int               AddCustomRectFontGlyph(SwFont* font, SwWchar id, int width, int height, float advance_x, const SwVec2& offset = SwVec2(0, 0));
    SwFontAtlasCustomRect*   GetCustomRectByIndex(int index) { SW_ASSERT(index >= 0); return &CustomRects[index]; }

    // [Internal]
    SW_API void              CalcCustomRectUV(const SwFontAtlasCustomRect* rect, SwVec2* out_uv_min, SwVec2* out_uv_max) const;
    SW_API bool              GetMouseCursorTexData(SwGuiMouseCursor cursor, SwVec2* out_offset, SwVec2* out_size, SwVec2 out_uv_border[2], SwVec2 out_uv_fill[2]);

    //-------------------------------------------
    // Members
    //-------------------------------------------

    SwFontAtlasFlags                    Flags;              // Build flags (see SwFontAtlasFlags_)
    SwTextureID                         TexID;              // User data to refer to the texture once it has been uploaded to user's graphic systems. It is passed back to you during rendering via the SwDrawCmd structure.
    int                                 TexDesiredWidth;    // Texture width desired by user before Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height.
    int                                 TexGlyphPadding;    // Padding between glyphs within texture in pixels. Defaults to 1. If your rendering method doesn't rely on bilinear filtering you may set this to 0 (will also need to set AntiAliasedLinesUseTex = false).
    bool                                Locked;             // Marked as Locked by SW::NewFrame() so attempt to modify the atlas will assert.

    // [Internal]
    // NB: Access texture data via GetTexData*() calls! Which will setup a default font for you.
    bool                                TexReady;           // Set when texture was built matching current font input
    bool                                TexPixelsUseColors; // Tell whether our texture data is known to use colors (rather than just alpha channel), in order to help backend select a format.
    unsigned char*                      TexPixelsAlpha8;    // 1 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight
    unsigned int*                       TexPixelsRGBA32;    // 4 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight * 4
    int                                 TexWidth;           // Texture width calculated during Build().
    int                                 TexHeight;          // Texture height calculated during Build().
    SwVec2                              TexUvScale;         // = (1.0f/TexWidth, 1.0f/TexHeight)
    SwVec2                              TexUvWhitePixel;    // Texture coordinates to a white pixel
    SwVector<SwFont*>                   Fonts;              // Hold all the fonts returned by AddFont*. Fonts[0] is the default font upon calling SW::NewFrame(), use SW::PushFont()/PopFont() to change the current font.
    SwVector<SwFontAtlasCustomRect>     CustomRects;    // Rectangles for packing custom texture data into the atlas.
    SwVector<SwFontConfig>              ConfigData;         // Configuration data
    SwVec4                              TexUvLines[SW_DRAWLIST_TEX_LINES_WIDTH_MAX + 1];  // UVs for baked anti-aliased lines

    // [Internal] Font builder
    const SwFontBuilderIO*              FontBuilderIO;      // Opaque interface to a font builder (default to stb_truetype, can be changed to use FreeType by defining SW_ENABLE_FREETYPE).
    unsigned int                        FontBuilderFlags;   // Shared flags (for all fonts) for custom font builder. THIS IS BUILD IMPLEMENTATION DEPENDENT. Per-font override is also available in SwFontConfig.

    // [Internal] Packing data
    int                                 PackIdMouseCursors; // Custom texture rectangle ID for white pixel and mouse cursors
    int                                 PackIdLines;        // Custom texture rectangle ID for baked anti-aliased lines

    // [Obsolete]
    //typedef SwFontAtlasCustomRect    CustomRect;         // OBSOLETED in 1.72+
    //typedef SwFontGlyphRangesBuilder GlyphRangesBuilder; // OBSOLETED in 1.67+
};

// Font runtime data and rendering
// SwFontAtlas automatically loads a default embedded font for you when you call GetTexDataAsAlpha8() or GetTexDataAsRGBA32().
struct SwFont
{
    // Members: Hot ~20/24 bytes (for CalcTextSize)
    SwVector<float>                 IndexAdvanceX;      // 12-16 // out //            // Sparse. Glyphs->AdvanceX in a directly indexable way (cache-friendly for CalcTextSize functions which only this this info, and are often bottleneck in large UI).
    float                           FallbackAdvanceX;   // 4     // out // = FallbackGlyph->AdvanceX
    float                           FontSize;           // 4     // in  //            // Height of characters/line, set during loading (don't change after loading)

    // Members: Hot ~28/40 bytes (for CalcTextSize + render loop)
    SwVector<SwWchar>               IndexLookup;        // 12-16 // out //            // Sparse. Index glyphs by Unicode code-point.
    SwVector<SwFontGlyph>           Glyphs;             // 12-16 // out //            // All glyphs.
    const SwFontGlyph*              FallbackGlyph;      // 4-8   // out // = FindGlyph(FontFallbackChar)

    // Members: Cold ~32/40 bytes
    SwFontAtlas*                    ContainerAtlas;     // 4-8   // out //            // What we has been loaded into
    const SwFontConfig*             ConfigData;         // 4-8   // in  //            // Pointer within ContainerAtlas->ConfigData
    short                           ConfigDataCount;    // 2     // in  // ~ 1        // Number of SwFontConfig involved in creating this font. Bigger than 1 when merging multiple font sources into one SwFont.
    SwWchar                         FallbackChar;       // 2     // out // = FFFD/'?' // Character used if a glyph isn't found.
    SwWchar                         EllipsisChar;       // 2     // out // = '...'    // Character used for ellipsis rendering.
    SwWchar                         DotChar;            // 2     // out // = '.'      // Character used for ellipsis rendering (if a single '...' character isn't found)
    bool                            DirtyLookupTables;  // 1     // out //
    float                           Scale;              // 4     // in  // = 1.f      // Base font scale, multiplied by the per-window font scale which you can adjust with SetWindowFontScale()
    float                           Ascent, Descent;    // 4+4   // out //            // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize]
    int                             MetricsTotalSurface;// 4     // out //            // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs)
    SwU8                            Used4kPagesMap[(SW_UNICODE_CODEPOINT_MAX + 1) / 4096 / 8]; // 2 bytes if SwWchar=SwWchar16, 34 bytes if SwWchar==SwWchar32. Store 1-bit for each block of 4K codepoints that has one active glyph. This is mainly used to facilitate iterations across all used codepoints.

    // Methods
    SW_API SwFont();
    SW_API ~SwFont();
    SW_API const SwFontGlyph*       FindGlyph(SwWchar c) const;
    SW_API const SwFontGlyph*       FindGlyphNoFallback(SwWchar c) const;
    float                           GetCharAdvance(SwWchar c) const { return ((int)c < IndexAdvanceX.Size) ? IndexAdvanceX[(int)c] : FallbackAdvanceX; }
    bool                            IsLoaded() const { return ContainerAtlas != NULL; }
    const char*                     GetDebugName() const { return ConfigData ? ConfigData->Name : "<unknown>"; }

    // 'max_width' stops rendering after a certain width (could be turned into a 2d size). FLT_MAX to disable.
    // 'wrap_width' enable automatic word-wrapping across multiple lines to fit into given width. 0.0f to disable.
    SW_API SwVec2                   CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end = NULL, const char** remaining = NULL) const; // utf8
    SW_API const char*              CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) const;
    SW_API void                     RenderChar(SwDrawList* draw_list, float size, const SwVec2& pos, SwU32 col, SwWchar c) const;
    SW_API void                     RenderText(SwDrawList* draw_list, float size, const SwVec2& pos, SwU32 col, const SwVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width = 0.0f, bool cpu_fine_clip = false) const;

    // [Internal] Don't use!
    SW_API void                     BuildLookupTable();
    SW_API void                     ClearOutputData();
    SW_API void                     GrowIndex(int new_size);
    SW_API void                     AddGlyph(const SwFontConfig* src_cfg, SwWchar c, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x);
    SW_API void                     AddRemapChar(SwWchar dst, SwWchar src, bool overwrite_dst = true); // Makes 'dst' character/glyph points to 'src' character/glyph. Currently needs to be called AFTER fonts have been built.
    SW_API void                     SetGlyphVisible(SwWchar c, bool visible);
    SW_API bool                     IsGlyphRangeUnused(unsigned int c_begin, unsigned int c_last);
};


//-----------------------------------------------------------------------------
// [SECTION] Viewports
//-----------------------------------------------------------------------------

// Flags stored in SwGuiViewport::Flags, giving indications to the platform backends.
enum SwGuiViewportFlags_
{
    SwGuiViewportFlags_None = 0,
    SwGuiViewportFlags_IsPlatformWindow = 1 << 0,   // Represent a Platform Window
    SwGuiViewportFlags_IsPlatformMonitor = 1 << 1,   // Represent a Platform Monitor (unused yet)
    SwGuiViewportFlags_OwnedByApp = 1 << 2,   // Platform Window: Was created/managed by the user application? (rather than our backend)
    SwGuiViewportFlags_NoDecoration = 1 << 3,   // Platform Window: Disable platform decorations: title bar, borders, etc. (generally set all windows, but if SwGuiConfigFlags_ViewportsDecoration is set we only set this on popups/tooltips)
    SwGuiViewportFlags_NoTaskBarIcon = 1 << 4,   // Platform Window: Disable platform task bar icon (generally set on popups/tooltips, or all windows if SwGuiConfigFlags_ViewportsNoTaskBarIcon is set)
    SwGuiViewportFlags_NoFocusOnAppearing = 1 << 5,   // Platform Window: Don't take focus when created.
    SwGuiViewportFlags_NoFocusOnClick = 1 << 6,   // Platform Window: Don't take focus when clicked on.
    SwGuiViewportFlags_NoInputs = 1 << 7,   // Platform Window: Make mouse pass through so we can drag this window while peaking behind it.
    SwGuiViewportFlags_NoRendererClear = 1 << 8,   // Platform Window: Renderer doesn't need to clear the framebuffer ahead (because we will fill it entirely).
    SwGuiViewportFlags_NoAutoMerge = 1 << 9,   // Platform Window: Avoid merging this window into another host window. This can only be set via SwGuiWindowClass viewport flags override (because we need to now ahead if we are going to create a viewport in the first place!).
    SwGuiViewportFlags_TopMost = 1 << 10,  // Platform Window: Display on top (for tooltips only).
    SwGuiViewportFlags_CanHostOtherWindows = 1 << 11,  // Viewport can host multiple imgui windows (secondary viewports are associated to a single window). // FIXME: In practice there's still probably code making the assumption that this is always and only on the MainViewport. Will fix once we add support for "no main viewport".

    // Output status flags (from Platform)
    SwGuiViewportFlags_IsSwmized = 1 << 12,  // Platform Window: Window is minimized, can skip render. When minimized we tend to avoid using the viewport pos/size for clipping window or testing if they are contained in the viewport.
    SwGuiViewportFlags_IsFocused = 1 << 13,  // Platform Window: Window is focused (last call to Platform_GetWindowFocus() returned true)
};

// - Currently represents the Platform Window created by the application which is hosting our  SwGui windows.
// - In 'docking' branch with multi-viewport enabled, we extend this concept to have multiple active viewports.
// - In the future we will extend this concept further to also represent Platform Monitor and support a "no main platform window" operation mode.
// - About Main Area vs Work Area:
//   - Main Area = entire viewport.
//   - Work Area = entire viewport minus sections used by main menu bars (for platform windows), or by task bar (for platform monitor).
//   - Windows are generally trying to stay within the Work Area of their host viewport.
struct SwGuiViewport
{
    SwGuiID                  ID;                     // Unique identifier for the viewport
    SwGuiViewportFlags       Flags;                  // See SwGuiViewportFlags_
    SwVec2                   Pos;                    // Main Area: Position of the viewport ( SwGui coordinates are the same as OS desktop/native coordinates)
    SwVec2                   Size;                   // Main Area: Size of the viewport.
    SwVec2                   WorkPos;                // Work Area: Position of the viewport minus task bars, menus bars, status bars (>= Pos)
    SwVec2                   WorkSize;               // Work Area: Size of the viewport minus task bars, menu bars, status bars (<= Size)
    float                    DpiScale;               // 1.0f = 96 DPI = No extra scale.
    SwGuiID                  ParentViewportId;       // (Advanced) 0: no parent. Instruct the platform backend to setup a parent/child relationship between platform windows.
    SwDrawData*              DrawData;               // The SwDrawData corresponding to this viewport. Valid after Render() and until the next call to NewFrame().

    // Platform/Backend Dependent Data
    void*                    RendererUserData;       // void* to hold custom data structure for the renderer (e.g. swap chain, framebuffers etc.). generally set by your Renderer_CreateWindow function.
    void*                    PlatformUserData;       // void* to hold custom data structure for the OS / platform (e.g. windowing info, render context). generally set by your Platform_CreateWindow function.
    void*                    PlatformHandle;         // void* for FindViewportByPlatformHandle(). (e.g. suggested to use natural platform handle such as HWND, GLFWWindow*, SDL_Window*)
    void*                    PlatformHandleRaw;      // void* to hold lower-level, platform-native window handle (under Win32 this is expected to be a HWND, unused for other platforms), when using an abstraction layer like GLFW or SDL (where PlatformHandle would be a SDL_Window*)
    bool                     PlatformWindowCreated;
    bool                     PlatformRequestMove;    // Platform window requested move (e.g. window was moved by the OS / host window manager, authoritative position will be OS window position)
    bool                     PlatformRequestResize;  // Platform window requested resize (e.g. window was resized by the OS / host window manager, authoritative size will be OS window size)
    bool                     PlatformRequestClose;   // Platform window requested closure (e.g. window was moved by the OS / host window manager, e.g. pressing ALT-F4)

    SwGuiViewport()        { memset(this, 0, sizeof(*this)); }
    ~SwGuiViewport() { SW_ASSERT(PlatformUserData == NULL && RendererUserData == NULL); }

    // Helpers
    SwVec2                 GetCenter() const { return SwVec2(Pos.x + Size.x * 0.5f, Pos.y + Size.y * 0.5f); }
    SwVec2                 GetWorkCenter() const { return SwVec2(WorkPos.x + WorkSize.x * 0.5f, WorkPos.y + WorkSize.y * 0.5f); }
};

//-----------------------------------------------------------------------------
// [SECTION] Platform Dependent Interfaces (for e.g. multi-viewport support)
//-----------------------------------------------------------------------------
// [BETA] (Optional) This is completely optional, for advanced users!
// If you are new to  SwGui and trying to integrate it into your engine, you can probably ignore this for now.
//
// This feature allows you to seamlessly drag  SwGui windows outside of your application viewport.
// This is achieved by creating new Platform/OS windows on the fly, and rendering into them.
//  SwGui manages the viewport structures, and the backend create and maintain one Platform/OS window for each of those viewports.
//
// See Glossary https://github.com/ocornut/imgui/wiki/Glossary for details about some of the terminology.
// See Thread https://github.com/ocornut/imgui/issues/1542 for gifs, news and questions about this evolving feature.
//
// About the coordinates system:
// - When multi-viewports are enabled, all  SwGui coordinates become absolute coordinates (same as OS coordinates!)
// - So e.g. SW::SetNextWindowPos(SwVec2(0,0)) will position a window relative to your primary monitor!
// - If you want to position windows relative to your main application viewport, use SW::GetMainViewport()->Pos as a base position.
//
// Steps to use multi-viewports in your application, when using a default backend from the examples/ folder:
// - Application:  Enable feature with 'io.ConfigFlags |= SwGuiConfigFlags_ViewportsEnable'.
// - Backend:      The backend initialization will setup all necessary SwGuiPlatformIO's functions and update monitors info every frame.
// - Application:  In your main loop, call SW::UpdatePlatformWindows(), SW::RenderPlatformWindowsDefault() after EndFrame() or Render().
// - Application:  Fix absolute coordinates used in SW::SetWindowPos() or SW::SetNextWindowPos() calls.
//
// Steps to use multi-viewports in your application, when using a custom backend:
// - Important:    THIS IS NOT EASY TO DO and comes with many subtleties not described here!
//                 It's also an experimental feature, so some of the requirements may evolve.
//                 Consider using default backends if you can. Either way, carefully follow and refer to examples/ backends for details.
// - Application:  Enable feature with 'io.ConfigFlags |= SwGuiConfigFlags_ViewportsEnable'.
// - Backend:      Hook SwGuiPlatformIO's Platform_* and Renderer_* callbacks (see below).
//                 Set 'io.BackendFlags |= SwGuiBackendFlags_PlatformHasViewports' and 'io.BackendFlags |= SwGuiBackendFlags_PlatformHasViewports'.
//                 Update SwGuiPlatformIO's Monitors list every frame.
//                 Update MousePos every frame, in absolute coordinates.
// - Application:  In your main loop, call SW::UpdatePlatformWindows(), SW::RenderPlatformWindowsDefault() after EndFrame() or Render().
//                 You may skip calling RenderPlatformWindowsDefault() if its API is not convenient for your needs. Read comments below.
// - Application:  Fix absolute coordinates used in SW::SetWindowPos() or SW::SetNextWindowPos() calls.
//
// About SW::RenderPlatformWindowsDefault():
// - This function is a mostly a _helper_ for the common-most cases, and to facilitate using default backends.
// - You can check its simple source code to understand what it does.
//   It basically iterates secondary viewports and call 4 functions that are setup in SwGuiPlatformIO, if available:
//     Platform_RenderWindow(), Renderer_RenderWindow(), Platform_SwapBuffers(), Renderer_SwapBuffers()
//   Those functions pointers exists only for the benefit of RenderPlatformWindowsDefault().
// - If you have very specific rendering needs (e.g. flipping multiple swap-chain simultaneously, unusual sync/threading issues, etc.),
//   you may be tempted to ignore RenderPlatformWindowsDefault() and write customized code to perform your renderingg.
//   You may decide to setup the platform_io's *RenderWindow and *SwapBuffers pointers and call your functions through those pointers,
//   or you may decide to never setup those pointers and call your code directly. They are a convenience, not an obligatory interface.
//-----------------------------------------------------------------------------

// (Optional) Access via SW::GetPlatformIO()
struct SwGuiPlatformIO
{
    //------------------------------------------------------------------
    // Input - Backend interface/functions + Monitor List
    //------------------------------------------------------------------

    // (Optional) Platform functions (e.g. Win32, GLFW, SDL2)
    // For reference, the second column shows which function are generally calling the Platform Functions:
    //   N = SW::NewFrame()                        ~ beginning of the  imgui frame: read info from platform/OS windows (latest size/position)
    //   F = SW::Begin(), SW::EndFrame()        ~ during the  imgui frame
    //   U = SW::UpdatePlatformWindows()           ~ after the  imgui frame: create and update all platform/OS windows
    //   R = SW::RenderPlatformWindowsDefault()    ~ render
    //   D = SW::DestroyPlatformWindows()          ~ shutdown
    // The general idea is that NewFrame() we will read the current Platform/OS state, and UpdatePlatformWindows() will write to it.
    //
    // The functions are designed so we can mix and match 2 mgui_impl_xxxx files, one for the Platform (~window/input handling), one for Renderer.
    // Custom engine backends will often provide both Platform and Renderer interfaces and so may not need to use all functions.
    // Platform functions are typically called before their Renderer counterpart, apart from Destroy which are called the other way.

    // Platform function --------------------------------------------------- Called by -----
    void    (*Platform_CreateWindow)(SwGuiViewport* vp);                    // . . U . .  // Create a new platform window for the given viewport
    void    (*Platform_DestroyWindow)(SwGuiViewport* vp);                   // N . U . D  //
    void    (*Platform_ShowWindow)(SwGuiViewport* vp);                      // . . U . .  // Newly created windows are initially hidden so SetWindowPos/Size/Title can be called on them before showing the window
    void    (*Platform_SetWindowPos)(SwGuiViewport* vp, SwVec2 pos);        // . . U . .  // Set platform window position (given the upper-left corner of client area)
    SwVec2(*Platform_GetWindowPos)(SwGuiViewport* vp);                    // N . . . .  //
    void    (*Platform_SetWindowSize)(SwGuiViewport* vp, SwVec2 size);      // . . U . .  // Set platform window client area size (ignoring OS decorations such as OS title bar etc.)
    SwVec2(*Platform_GetWindowSize)(SwGuiViewport* vp);                   // N . . . .  // Get platform window client area size
    void    (*Platform_SetWindowFocus)(SwGuiViewport* vp);                  // N . . . .  // Move window to front and set input focus
    bool    (*Platform_GetWindowFocus)(SwGuiViewport* vp);                  // . . U . .  //
    bool    (*Platform_GetWindowSwmized)(SwGuiViewport* vp);              // N . . . .  // Get platform window minimized state. When minimized, we generally won't attempt to get/set size and contents will be culled more easily
    void    (*Platform_SetWindowTitle)(SwGuiViewport* vp, const char* str); // . . U . .  // Set platform window title (given an UTF-8 string)
    void    (*Platform_SetWindowAlpha)(SwGuiViewport* vp, float alpha);     // . . U . .  // (Optional) Setup global transparency (not per-pixel transparency)
    void    (*Platform_UpdateWindow)(SwGuiViewport* vp);                    // . . U . .  // (Optional) Called by UpdatePlatformWindows(). Optional hook to allow the platform backend from doing general book-keeping every frame.
    void    (*Platform_RenderWindow)(SwGuiViewport* vp, void* render_arg);  // . . . R .  // (Optional) Main rendering (platform side! This is often unused, or just setting a "current" context for OpenGL bindings). 'render_arg' is the value passed to RenderPlatformWindowsDefault().
    void    (*Platform_SwapBuffers)(SwGuiViewport* vp, void* render_arg);   // . . . R .  // (Optional) Call Present/SwapBuffers (platform side! This is often unused!). 'render_arg' is the value passed to RenderPlatformWindowsDefault().
    float   (*Platform_GetWindowDpiScale)(SwGuiViewport* vp);               // N . . . .  // (Optional) [BETA] FIXME-DPI: DPI handling: Return DPI scale for this viewport. 1.0f = 96 DPI.
    void    (*Platform_OnChangedViewport)(SwGuiViewport* vp);               // . F . . .  // (Optional) [BETA] FIXME-DPI: DPI handling: Called during Begin() every time the viewport we are outputting into changes, so backend has a chance to swap fonts to adjust style.
    int     (*Platform_CreateVkSurface)(SwGuiViewport* vp, SwU64 vk_inst, const void* vk_allocators, SwU64* out_vk_surface); // (Optional) For a Vulkan Renderer to call into Platform code (since the surface creation needs to tie them both).

    // (Optional) Renderer functions (e.g. DirectX, OpenGL, Vulkan)
    void    (*Renderer_CreateWindow)(SwGuiViewport* vp);                    // . . U . .  // Create swap chain, frame buffers etc. (called after Platform_CreateWindow)
    void    (*Renderer_DestroyWindow)(SwGuiViewport* vp);                   // N . U . D  // Destroy swap chain, frame buffers etc. (called before Platform_DestroyWindow)
    void    (*Renderer_SetWindowSize)(SwGuiViewport* vp, SwVec2 size);      // . . U . .  // Resize swap chain, frame buffers etc. (called after Platform_SetWindowSize)
    void    (*Renderer_RenderWindow)(SwGuiViewport* vp, void* render_arg);  // . . . R .  // (Optional) Clear framebuffer, setup render target, then render the viewport->DrawData. 'render_arg' is the value passed to RenderPlatformWindowsDefault().
    void    (*Renderer_SwapBuffers)(SwGuiViewport* vp, void* render_arg);   // . . . R .  // (Optional) Call Present/SwapBuffers. 'render_arg' is the value passed to RenderPlatformWindowsDefault().

    // (Optional) Monitor list
    // - Updated by: app/backend. Update every frame to dynamically support changing monitor or DPI configuration.
    // - Used by:  imgui to query DPI info, clamp popups/tooltips within same monitor and not have them straddle monitors.
    SwVector<SwGuiPlatformMonitor>  Monitors;

    //------------------------------------------------------------------
    // Output - List of viewports to render into platform windows
    //------------------------------------------------------------------

    // Viewports list (the list is updated by calling SW::EndFrame or SW::Render)
    // (in the future we will attempt to organize this feature to remove the need for a "main viewport")
    SwVector<SwGuiViewport*>        Viewports;                              // Main viewports, followed by all secondary viewports.
    SwGuiPlatformIO() { memset(this, 0, sizeof(*this)); }     // Zero clear
};

//-----------------------------------------------------------------------------
// [SECTION] Misc data structures
//-----------------------------------------------------------------------------

// Shared state of InputText(), passed as an argument to your callback when a SwGuiInputTextFlags_Callback* flag is used.
// The callback function should return 0 by default.
// Callbacks (follow a flag name and see comments in SwGuiInputTextFlags_ declarations for more details)
// - SwGuiInputTextFlags_CallbackEdit:        Callback on buffer edit (note that InputText() already returns true on edit, the callback is useful mainly to manipulate the underlying buffer while focus is active)
// - SwGuiInputTextFlags_CallbackAlways:      Callback on each iteration
// - SwGuiInputTextFlags_CallbackCompletion:  Callback on pressing TAB
// - SwGuiInputTextFlags_CallbackHistory:     Callback on pressing Up/Down arrows
// - SwGuiInputTextFlags_CallbackCharFilter:  Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard.
// - SwGuiInputTextFlags_CallbackResize:      Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow.
struct SwGuiInputTextCallbackData
{
    SwGuiContext*         Ctx;            // Parent UI context
    SwGuiInputTextFlags   EventFlag;      // One SwGuiInputTextFlags_Callback*    // Read-only
    SwGuiInputTextFlags   Flags;          // What user passed to InputText()      // Read-only
    void*                 UserData;       // What user passed to InputText()      // Read-only

    // Arguments for the different callback events
    // - To modify the text buffer in a callback, prefer using the InsertChars() / DeleteChars() function. InsertChars() will take care of calling the resize callback if necessary.
    // - If you know your edits are not going to resize the underlying buffer allocation, you may modify the contents of 'Buf[]' directly. You need to update 'BufTextLen' accordingly (0 <= BufTextLen < BufSize) and set 'BufDirty'' to true so InputText can update its internal state.
    SwWchar               EventChar;      // Character input                      // Read-write   // [CharFilter] Replace character with another one, or set to zero to drop. return 1 is equivalent to setting EventChar=0;
    SwGuiKey              EventKey;       // Key pressed (Up/Down/TAB)            // Read-only    // [Completion,History]
    char*                 Buf;            // Text buffer                          // Read-write   // [Resize] Can replace pointer / [Completion,History,Always] Only write to pointed data, don't replace the actual pointer!
    int                   BufTextLen;     // Text length (in bytes)               // Read-write   // [Resize,Completion,History,Always] Exclude zero-terminator storage. In C land: == strlen(some_text), in C++ land: string.length()
    int                   BufSize;        // Buffer size (in bytes) = capacity+1  // Read-only    // [Resize,Completion,History,Always] Include zero-terminator storage. In C land == ARRAYSIZE(my_char_array), in C++ land: string.capacity()+1
    bool                  BufDirty;       // Set if you modify Buf/BufTextLen!    // Write        // [Completion,History,Always]
    int                   CursorPos;      //                                      // Read-write   // [Completion,History,Always]
    int                   SelectionStart; //                                      // Read-write   // [Completion,History,Always] == to SelectionEnd when no selection)
    int                   SelectionEnd;   //                                      // Read-write   // [Completion,History,Always]

    // Helper functions for text manipulation.
    // Use those function to benefit from the CallbackResize behaviors. Calling those function reset the selection.
    SW_API                SwGuiInputTextCallbackData();
    SW_API void           DeleteChars(int pos, int bytes_count);
    SW_API void           InsertChars(int pos, const char* text, const char* text_end = NULL);
    void                  SelectAll() { SelectionStart = 0; SelectionEnd = BufTextLen; }
    void                  ClearSelection() { SelectionStart = SelectionEnd = BufTextLen; }
    bool                  HasSelection() const { return SelectionStart != SelectionEnd; }
};

// Resizing callback data to apply custom constraint. As enabled by SetNextWindowSizeConstraints(). Callback is called during the next Begin().
// NB: For basic min/max size constraint on each axis you don't need to use the callback! The SetNextWindowSizeConstraints() parameters are enough.
struct SwGuiSizeCallbackData
{
    void*                 UserData;       // Read-only.   What user passed to SetNextWindowSizeConstraints(). Generally store an integer or float in here (need reinterpret_cast<>).
    SwVec2                Pos;            // Read-only.   Window position, for reference.
    SwVec2                CurrentSize;    // Read-only.   Current window size.
    SwVec2                DesiredSize;    // Read-write.  Desired size, based on user's mouse position. Write to this field to restrain resizing.
};

// [ALPHA] Rarely used / very advanced uses only. Use with SetNextWindowClass() and DockSpace() functions.
// Important: the content of this class is still highly WIP and likely to change and be refactored
// before we stabilize Docking features. Please be mindful if using this.
// Provide hints:
// - To the platform backend via altered viewport flags (enable/disable OS decoration, OS task bar icons, etc.)
// - To the platform backend for OS level parent/child relationships of viewport.
// - To the docking system for various options and filtering.
struct SwGuiWindowClass
{
    SwGuiID               ClassId;                    // User data. 0 = Default class (unclassed). Windows of different classes cannot be docked with each others.
    SwGuiID               ParentViewportId;           // Hint for the platform backend. -1: use default. 0: request platform backend to not parent the platform. != 0: request platform backend to create a parent<>child relationship between the platform windows. Not conforming backends are free to e.g. parent every viewport to the main viewport or not.
    SwGuiViewportFlags    ViewportFlagsOverrideSet;   // Viewport flags to set when a window of this class owns a viewport. This allows you to enforce OS decoration or task bar icon, override the defaults on a per-window basis.
    SwGuiViewportFlags    ViewportFlagsOverrideClear; // Viewport flags to clear when a window of this class owns a viewport. This allows you to enforce OS decoration or task bar icon, override the defaults on a per-window basis.
    SwGuiTabItemFlags     TabItemFlagsOverrideSet;    // [EXPERIMENTAL] TabItem flags to set when a window of this class gets submitted into a dock node tab bar. May use with SwGuiTabItemFlags_Leading or SwGuiTabItemFlags_Trailing.
    SwGuiDockNodeFlags    DockNodeFlagsOverrideSet;   // [EXPERIMENTAL] Dock node flags to set when a window of this class is hosted by a dock node (it doesn't have to be selected!)
    bool                  DockingAlwaysTabBar;        // Set to true to enforce single floating windows of this class always having their own docking node (equivalent of setting the global io.ConfigDockingAlwaysTabBar)
    bool                  DockingAllowUnclassed;      // Set to true to allow windows of this class to be docked/merged with an unclassed window. // FIXME-DOCK: Move to DockNodeFlags override?

    SwGuiWindowClass() { memset(this, 0, sizeof(*this)); ParentViewportId = (SwGuiID)-1; DockingAllowUnclassed = true; }
};

// Data payload for Drag and Drop operations: AcceptDragDropPayload(), GetDragDropPayload()
struct SwGuiPayload
{
    // Members
    void*                 Data;               // Data (copied and owned by  imgui)
    int                   DataSize;           // Data size

    // [Internal]
    SwGuiID               SourceId;           // Source item id
    SwGuiID               SourceParentId;     // Source parent id (if available)
    int                   DataFrameCount;     // Data timestamp
    char                  DataType[32 + 1];   // Data type tag (short user-supplied string, 32 characters max)
    bool                  Preview;            // Set when AcceptDragDropPayload() was called and mouse has been hovering the target item (nb: handle overlapping drag targets)
    bool                  Delivery;           // Set when AcceptDragDropPayload() was called and mouse button is released over the target item.

    SwGuiPayload() { Clear(); }
    void Clear() { SourceId = SourceParentId = 0; Data = NULL; DataSize = 0; memset(DataType, 0, sizeof(DataType)); DataFrameCount = -1; Preview = Delivery = false; }
    bool IsDataType(const char* type) const { return DataFrameCount != -1 && strcmp(type, DataType) == 0; }
    bool IsPreview() const { return Preview; }
    bool IsDelivery() const { return Delivery; }
};

// Sorting specification for one column of a table (sizeof == 12 bytes)
struct SwGuiTableColumnSortSpecs
{
    SwGuiID                     ColumnUserID;       // User id of the column (if specified by a TableSetupColumn() call)
    SwS16                       ColumnIndex;        // Index of the column
    SwS16                       SortOrder;          // Index within parent SwGuiTableSortSpecs (always stored in order starting from 0, tables sorted on a single criteria will always have a 0 here)
    SwGuiSortDirection          SortDirection : 8;  // SwGuiSortDirection_Ascending or SwGuiSortDirection_Descending (you can use this or SortSign, whichever is more convenient for your sort function)

    SwGuiTableColumnSortSpecs() { memset(this, 0, sizeof(*this)); }
};

// Sorting specifications for a table (often handling sort specs for a single column, occasionally more)
// Obtained by calling TableGetSortSpecs().
// When 'SpecsDirty == true' you can sort your data. It will be true with sorting specs have changed since last call, or the first time.
// Make sure to set 'SpecsDirty = false' after sorting, else you may wastefully sort your data every frame!
struct SwGuiTableSortSpecs
{
    const SwGuiTableColumnSortSpecs*    Specs;     // Pointer to sort spec array.
    int                                 SpecsCount;     // Sort spec count. Most often 1. May be > 1 when SwGuiTableFlags_SortMulti is enabled. May be == 0 when SwGuiTableFlags_SortTristate is enabled.
    bool                                SpecsDirty;     // Set to true when specs have changed since last time! Use this to sort again, then clear the flag.

    SwGuiTableSortSpecs() { memset(this, 0, sizeof(*this)); }
};

//-----------------------------------------------------------------------------
// [SECTION] Platform Dependent Interfaces
//-----------------------------------------------------------------------------


// (Optional) This is required when enabling multi-viewport. Represent the bounds of each connected monitor/display and their DPI.
// We use this information for multiple DPI support + clamping the position of popups and tooltips so they don't straddle multiple monitors.
struct SwGuiPlatformMonitor
{
    SwVec2  MainPos, MainSize;      // Coordinates of the area displayed on this monitor (Min = upper left, Max = bottom right)
    SwVec2  WorkPos, WorkSize;      // Coordinates without task bars / side bars / menu bars. Used to avoid positioning popups/tooltips inside this region. If you don't have this info, please copy the value for MainPos/MainSize.
    float   DpiScale;               // 1.0f = 96 DPI
    void* PlatformHandle;         // Backend dependant data (e.g. HMONITOR, GLFWmonitor*, SDL Display Index, NSScreen*)
    SwGuiPlatformMonitor() { MainPos = MainSize = WorkPos = WorkSize = SwVec2(0, 0); DpiScale = 1.0f; PlatformHandle = NULL; }
};

// (Optional) Support for IME (Input Method Editor) via the io.SetPlatformImeDataFn() function.
struct SwGuiPlatformImeData
{
    bool      WantVisible;        // A widget wants the IME to be visible
    SwVec2    InputPos;           // Position of the input cursor
    float     InputLineHeight;    // Line height

    SwGuiPlatformImeData() { memset(this, 0, sizeof(*this)); }
};


#endif // !__SW_H__
